C# 在文本框中显示数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1129604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:53:35  来源:igfitidea点击:

Display data on a text box

c#sql-server

提问by MAC

i have one database, and it contains some columns. My requirement is that how to display each of the data that i stored in the databse on a text box? my code is shown below (after the connection string)

我有一个数据库,它包含一些列。我的要求是如何在文本框中显示我存储在数据库中的每个数据?我的代码如下所示(在连接字符串之后)

conn.Open();
mycommnd.ExecuteScalar();
SqlDataAdapter da = new SqlDataAdapter(mycommnd);
DataTable dt = new DataTable();
da.Fill(dt);

What changes that i make after da.Fill(dt) for displaying data on the text box.

在 da.Fill(dt) 之后我做了哪些更改以在文本框中显示数据。

采纳答案by Aamir

Something like:

就像是:

textBox1.Text = dt.Rows[0].ItemArray[0].ToString();

Depends on the name of your textbox and which value you want to put into that text box.

取决于文本框的名称以及要放入该文本框中的值。

回答by hadi teo

You need to loop inside each columns in the DataTable to get the values and then concatenate them into a string and assign it to a textbox.Text property

您需要在 DataTable 中的每一列内循环以获取值,然后将它们连接成一个字符串并将其分配给 textbox.Text 属性

        DataTable dt = new DataTable();
        TextBox ResultTextBox;

        StringBuilder result = new StringBuilder();

        foreach(DataRow dr in dt.Rows)
        {
            foreach(DataColumn dc in dt.Columns)
            {
                result.Append(dr[dc].ToString());
            }
        }

        ResultTextBox.Text = result.ToString();

回答by Aragorn

One form of using the ExecuteScalar:

使用 ExecuteScalar 的一种形式:

textBox.Text = mycommnd.ExecuteScalar().ToString();

回答by Fredrik M?rk

The DataTable consists of rows and columns, that you can reach in some different ways:

DataTable 由行和列组成,您可以通过一些不同的方式访问它们:

// get value from first row, first column
myTextBox.Text = dt.Rows[0][0]; 
// get value from first row, column named "First",
myTextBox.Text = dt.Rows[0]["First"];