简体   繁体   English

从数据库中读取数据并将其显示在文本字段中

[英]Reading data from the database and displaying it in a text field

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();
    }
}

} }

I have the following program where I'm reading the values from the table and want to display the table values in a text field upon button click. 我有以下程序,我正在从表中读取值,并希望在按钮单击时在文本字段中显示表值。 Now when I click on the button, it just keeps on displaying first table in the listbox. 现在当我点击按钮时,它只是继续显示列表框中的第一个表

Can someone guide me through my error? 有人可以指导我完成我的错误吗?

I suppose you need to display the Values existing in the DataRow of a DataTable . 我想你需要显示DataTableDataRow中存在的值。 In the code snippet below, columnName is referring to the Column of the testing Table , that you want to show in the ListBox . 在下面的代码片段中,columnName指的是要在ListBox显示的testing TableColumn

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

OR 要么

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

tables.TableName gives the name of the table which is "First Table" itself.So,it keeps on showing the same. tables.TableName给出了表的名称,即“First Table”本身。因此,它继续显示相同的内容。

Better use this code. 更好地使用此代码。

    if(!ds.Tables.Count>1)
 { 
foreach (DataRow row in ds.Tables[0].Rows) 
{
        ListBox1.Items.Add(row["columnName"].ToString());
 } 
}
       SqlCommand cmd = new SqlCommand("select * from testing", conn);
            MySqlDataReader msqlreader = cmd.ExecuteReader();
            while (msqlreader.Read())
            { 
            listBox1.Items.Add(msqlreader(0);
            }

Im not sure if this is what you need, but hope it helps 我不确定这是否是你需要的,但希望它有所帮助

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

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