Reputation: 43
I want to access value of 2nd row 1st column from an existing data table.. I tried with this code..
DataTable dt = new DataTable("Aqua");
for (int i = 0; i < dt.Rows.Count; i++)
{
datagridItemEntry.Rows[i].Cells[0].Value = dt.Rows[i]["SlNo"];
}
Data table name is "Aqua".. But nothing is working.. Help me out..
Upvotes: 0
Views: 813
Reputation: 148110
You are just declaring the DataTable
but no data is loaded so your loop wont execute as the dt.Rows.Count
is zero. This is what is expected behavior. You probably need to load data before the loop.
DataTable dt = new DataTable("Aqua");
//Load data in to data table here.
for (int i = 0; i < dt.Rows.Count; i++)
{
datagridItemEntry.Rows[i].Cells[0].Value = dt.Rows[i]["SlNo"];
}
Edit To access Second Row first column, then just put a condition to assure you have required number of rows and columns, if the rows and column count could be less then the required.
if(dt.Rows.Count > 0 && dt.Rows.Columns.Count > 0)
str = dt.Rows[1][0].ToString();
Upvotes: 2
Reputation: 477
Try this..It may help you out.
string temp;
String query="Your Query that retrieves the data you want";
SqlCommand cmd=new SqlCommand(query,con);//con is your connection string
DataTable dt=new DataTable();
con.Open();//Open your connection to database
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(dt);
if(dt.Rows.Count>0)
{
temp=dt.Rows[0]["SlNo"].ToString();
}
con.Close();
Upvotes: 1