【问题标题】:Reading data from the database and displaying it in a text field从数据库中读取数据并将其显示在文本字段中
【发布时间】:2012-10-26 09:58:10
【问题描述】:
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();
    }
}

}

我有以下程序,我正在从表中读取值,并希望在单击按钮时在文本字段中显示表值。现在,当我单击按钮时,它会继续在列表框中显示 first table

有人可以指导我解决我的错误吗?

【问题讨论】:

    标签: c# asp.net dataset sqldataadapter


    【解决方案1】:

    我想您需要显示存在于DataTableDataRow 中的值。在下面的代码 sn-p 中,columnName 指的是 testing Table 中的 Column,您希望在 ListBox 中显示。

    foreach (DataRow row in ds.Tables["First Table"].Rows)
    {
        ListBox1.Items.Add(row["columnName"].ToString());
    }
    

    foreach (DataRow row in ds.Tables[0].Rows)
    {
        ListBox1.Items.Add(row["columnName"].ToString());
    }
    

    【讨论】:

    • 谢谢!像魅力一样工作!
    【解决方案2】:

    tables.TableName 给出了表的名称,它本身就是“第一表”。所以,它一直显示相同。

    最好使用此代码。

        if(!ds.Tables.Count>1)
     { 
    foreach (DataRow row in ds.Tables[0].Rows) 
    {
            ListBox1.Items.Add(row["columnName"].ToString());
     } 
    }
    

    【讨论】:

    • @FurqanSafdar 是的,因为答案是一样的:=)
    • @FurqanSafdar:证明你可能是对的。没关系,我为你们俩+1(你们是第一个,我认为投票支持和鼓励低代表用户很重要)。 ;-)
    【解决方案3】:
           SqlCommand cmd = new SqlCommand("select * from testing", conn);
                MySqlDataReader msqlreader = cmd.ExecuteReader();
                while (msqlreader.Read())
                { 
                listBox1.Items.Add(msqlreader(0);
                }
    

    我不确定这是否是您需要的,但希望对您有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多