C# 从数据库读取数据并将其显示在文本字段中
} 我有下面的程序,我正在从表中读取值,并希望在单击按钮时在文本字段中显示表值。现在,当我单击按钮时,它会继续在列表框中显示第一个表C# 从数据库读取数据并将其显示在文本字段中,c#,asp.net,dataset,sqldataadapter,C#,Asp.net,Dataset,Sqldataadapter,} 我有下面的程序,我正在从表中读取值,并希望在单击按钮时在文本字段中显示表值。现在,当我单击按钮时,它会继续在列表框中显示第一个表 有人能帮我解决我的错误吗?我想您需要显示数据表的数据行中存在的值。在下面的代码段中,columnName指的是测试表的列,您希望在列表框中显示该列 using System; using System.Data; using System.Data.SqlClient; using System.Configuration; public partial cla
有人能帮我解决我的错误吗?我想您需要显示
数据表的数据行中存在的值。在下面的代码段中,columnName指的是测试表
的列
,您希望在列表框
中显示该列
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(
"Data Source=PTZ1\\SQLEXPRESS;Initial Catalog = test; Integrated Security=SSPI;User ID=sa; Password=sa@; Trusted_Connection=True;");
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("select * from testing", conn);
adapter.SelectCommand = cmd;
adapter.Fill(ds, "First Table");
foreach (DataTable tables in ds.Tables)
{
ListBox1.Items.Add(tables.TableName);
}
conn.Close();
}
catch (Exception ex)
{
Label1.Text = "Error in execution " + ex.ToString();
}
}
或
我想您需要显示DataTable
的DataRow
中存在的值。在下面的代码段中,columnName指的是测试表
的列
,您希望在列表框
中显示该列
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(
"Data Source=PTZ1\\SQLEXPRESS;Initial Catalog = test; Integrated Security=SSPI;User ID=sa; Password=sa@; Trusted_Connection=True;");
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("select * from testing", conn);
adapter.SelectCommand = cmd;
adapter.Fill(ds, "First Table");
foreach (DataTable tables in ds.Tables)
{
ListBox1.Items.Add(tables.TableName);
}
conn.Close();
}
catch (Exception ex)
{
Label1.Text = "Error in execution " + ex.ToString();
}
}
或
tables.TableName
给出了表的名称,即“第一个表”本身。因此,它继续显示相同的名称
最好使用这个代码
foreach (DataRow row in ds.Tables[0].Rows)
{
ListBox1.Items.Add(row["columnName"].ToString());
}
tables.TableName
给出了表的名称,即“第一个表”本身。因此,它继续显示相同的名称
最好使用这个代码
foreach (DataRow row in ds.Tables[0].Rows)
{
ListBox1.Items.Add(row["columnName"].ToString());
}
我不确定这是否是你需要的,但希望它能帮助你
我不确定这是否是您所需要的,但希望能有所帮助谢谢!工作得很有魅力!谢谢工作得很有魅力@FurqanSafdar是的,因为答案是一样的:=)@FurqanSafdar:这证明你可能是对的。没关系,我感谢你们两位(你们是第一位,我认为投票支持和鼓励低代表性用户很重要)。;-)@FurqanSafdar是的,因为答案是一样的:=)@FurqanSafdar:这证明你可能是对的。没关系,我感谢你们两位(你们是第一位,我认为投票支持和鼓励低代表性用户很重要)。;-)
SqlCommand cmd = new SqlCommand("select * from testing", conn);
MySqlDataReader msqlreader = cmd.ExecuteReader();
while (msqlreader.Read())
{
listBox1.Items.Add(msqlreader(0);
}