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();
}
}
}
我有以下程序,我正在从表中读取值,并希望在单击按钮时在文本字段中显示表值。现在,当我点击按钮时,它会继续在列表框中显示第一个表。
有人可以指导我完成错误吗?
答案 0 :(得分:3)
我想您需要显示DataRow
DataTable
中存在的值。在下面的代码段中,columnName指的是您要在Column
中显示的testing Table
的{{1}}。
ListBox
OR
foreach (DataRow row in ds.Tables["First Table"].Rows)
{
ListBox1.Items.Add(row["columnName"].ToString());
}
答案 1 :(得分:1)
tables.TableName
给出了“First Table”本身的表名。所以它继续显示相同的内容。
最好使用此代码。
if(!ds.Tables.Count>1)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
ListBox1.Items.Add(row["columnName"].ToString());
}
}
答案 2 :(得分:0)
SqlCommand cmd = new SqlCommand("select * from testing", conn);
MySqlDataReader msqlreader = cmd.ExecuteReader();
while (msqlreader.Read())
{
listBox1.Items.Add(msqlreader(0);
}
我不确定这是否是您所需要的,但希望有所帮助