C# 如何从datatable到textbox获取列值?
我想得到列中的所有值。。 这是我的密码C# 如何从datatable到textbox获取列值?,c#,C#,我想得到列中的所有值。。 这是我的密码 private void btnLeftArrow_Click(object sender, EventArgs e) { if (con.State == ConnectionState.Open) { con.Close(); } con.Open(); DataTable dt=new DataTable(); SqlCommand cmd = new SqlCommand("selec
private void btnLeftArrow_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
DataTable dt=new DataTable();
SqlCommand cmd = new SqlCommand("select * from Group_Name", con);
object obj = cmd.ExecuteScalar();
if (obj != null)
txtGroupName.Text = obj.ToString();
con.Close();
}
它只显示第一个值..但我想为每次单击按钮获取其他值。。
我的表只有一列返回第一行的第一列。将忽略所有其他列或行
若要返回列中的所有值,至少需要使用and with while语句。顺便一提,一行一行地阅读你的读者
比如,
...
SqlCommand cmd = new SqlCommand("select * from Group_Name", con);
using(SqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
string firstcolumn = reader[0].ToString(); // It is zero-indexed.
}
}
但是看起来您想将这些值添加到文本框中,您可以在列表中添加一个空格,然后您可以将它们用于文本框中,比如(我假设您的值是字符串
)
List List=新列表();
...
...
while(reader.Read())
{
添加(读卡器[0].ToString());
}
TextBox1.Text=String.Join(“,list.ToArray());
如果使用.NET 4或更高版本,则不需要使用.ToArray()
,因为这需要一个IEnumerable
ExecuteScalr
返回一个值,其中asExecuteReader
返回行集合。
因此,如果您想要所有结果,请使用ExecuteReader
while(dt.Rows.Count>0)
{
txtGroupName.Text=dt.Rows[0]["column_name"].ToString();
}
检查此链接:对不起,我不明白为什么选择此答案。这甚至没有解释如何根据SqlCommand
的结果设置dt
。
while(dt.Rows.Count>0)
{
txtGroupName.Text=dt.Rows[0]["column_name"].ToString();
}