[英]How to access the a particular value from the data table?
我想从现有数据表访问第二行第一列的值。我尝试使用此代码。
DataTable dt = new DataTable("Aqua");
for (int i = 0; i < dt.Rows.Count; i++)
{
datagridItemEntry.Rows[i].Cells[0].Value = dt.Rows[i]["SlNo"];
}
数据表的名称是“ Aqua”。。但是什么都没有用。
您只是声明了DataTable
但未加载任何数据,因此您的循环将不会执行,因为dt.Rows.Count
为零。 这是预期的行为。 您可能需要在循环之前加载数据。
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"];
}
编辑要访问第二行第一列,然后放置一个条件以确保您具有所需的行数和列数(如果行数和列数可能少于所需数)。
if(dt.Rows.Count > 0 && dt.Rows.Columns.Count > 0)
str = dt.Rows[1][0].ToString();
试试这个。可能会帮到您。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.