如何访问数据表中的特定值

本文关键字:数据表 何访问 访问 | 更新日期: 2023-09-27 17:57:10

我想从现有数据表中访问第 2 行第 1 列的值。我尝试使用此代码..

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();