简体   繁体   English

尝试从DataTable获取第二行

[英]Trying to get second row from DataTable

I'm trying to retrieve the second row from a DataTable but this is not returning a value. 我正在尝试从DataTable检索第二行,但这没有返回值。 What could be the problem as the DropDown populates just fine. 当DropDown填充得很好时,可能是什么问题。

            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt);
                DropDown.DataSource = dt;
                DropDown.DataTextField = "FirstName";
                DropDown.DataValueField = "FirstName";
                DropDown.DataBind();
                con.Close();

                var secondRow = dt.Rows[2].ToString(); // This should return the second row in my datatable.
            }

DataTable.Rows[int] will give you the DataRow object. DataTable.Rows[int]将为您提供DataRow对象。 If you do dt.Rows[2].ToString() , you are going to get the string representation of the object type. 如果执行dt.Rows[2].ToString() ,则将获取对象类型的字符串表示形式。

The index starts at 0 . 索引从0开始。 Hence for 2nd row, you will query dt.Rows[1] . 因此,对于第二行,您将查询dt.Rows[1] Further, You can extract the value of a column in the row and for that, you have to mention the column index or name like - dt.Rows[1][0] or dt.Rows[1]["col1"] 此外,您可以提取行中的列的值,为此,您必须提及列索引或名称,例如dt.Rows[1][0]dt.Rows[1]["col1"]

You can also loop through all the columns in the row like below: 您还可以像下面这样遍历行中的所有列:

foreach (DataColumn col in dt.Columns)
{
  var columnValue = dt.Rows[1][col];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM