Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot apply indexing with to an expression of type 'system.data.datatable'

I have a Login table in SQL Server 2008 and I want to check for a valid user in DataColumn.

I was trying to retrieve value from DataColumn by indexing, but got the error..

cannot apply indexing with to an expression of type 'system.data.datatable'.

Here is the code:

 string connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=DRZare;Integrated Security=true;";
 SqlConnection LOGINCONNECTION = new SqlConnection(connectionString);

 string commandText = "select * from Login where UserName = @User and Password = @Pass";
 SqlCommand cmdlogin = new SqlCommand(commandText,    LOGINCONNECTION);

 cmdlogin.Parameters.AddWithValue("@User", TextBox5.Text);
 cmdlogin.Parameters.AddWithValue("@Pass",TextBox6.Text);

 LOGINCONNECTION.Open();
 DataTable logintable = new DataTable();
 logintable.Load(cmdlogin.ExecuteReader());

 for (int i = 0; i < logintable.Rows.Count; i++ )
 {
     User = Convert.ToString(logintable[i]["UserName"]);
     string Pass = Convert.ToString(logintable[i]["Password"]);
 }

Help me out.

like image 264
F.P Avatar asked Dec 21 '25 18:12

F.P


2 Answers

Error message says clearly where is the problem. You can't use indexer on DataTable. But you can use it with DataRow.

Change to:

 foreach (DataRow row in loginTable.Rows )
 { 
     string User = Convert.ToString(row["UserName"]);
     string Pass = Convert.ToString(row["Password"]);
 }
like image 191
Lukasz Szozda Avatar answered Dec 23 '25 07:12

Lukasz Szozda


Thanks for your help. The code was changed into this and now it works correctly.

string User = Convert.ToString(logintable.Rows[i]["UserName"]);
                string Pass = Convert.ToString(logintable.Rows[i]["Password"]
like image 27
F.P Avatar answered Dec 23 '25 08:12

F.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!