如何使用C#.net将数据从sql数据库显示到文本框 [英] how to display data from sql database to textbox using C#.net

查看:209
本文介绍了如何使用C#.net将数据从sql数据库显示到文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



i在C#中有一个胜利形式.net
这个形式的
有一行数字

i在sql db中保存数字

i想从sql向textbox插入数字?

怎么做?

hi
i have a win form in C#.net
in this form there are row of number
i save numbers in sql db
i want to insert numbers to textbox from sql?
how do it?

推荐答案

嗨ely z,



您可以使用:



Hi ely z,

You can use this :

SqlConnection Conn = new SqlConnection(Connection_String);
SqlCommand Comm1 = new SqlCommand(Command, Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
    textBox.Text = DR1.GetValue(0).ToString();
}
Conn.Close();





另一种方式:





another way :

SqlConnection Conn = new SqlConnection(Connection_String);
SqlCommand Comm1 = new SqlCommand(Command, Conn);
Conn.Open();
textBox.Text = Comm1.ExecuteScalar();
Conn.Close();









I希望你的帮助,

:)





I hope yhis help,
:)


1)确保你的TextBox是MultiLine

2)建立与数据库的连接。

3)设置一个SQL命令来读取数字。

4)清除TextBox内容。

5)从中读取数据DataBase并将每一行添加到TextBox。



下面是一个示例,但请记住它不适用于您:您的数据库和表将被命名另外,你需要获取数字并将它们转换为字符串,而不是名为message的字符串字段:

1) Ensure your TextBox is MultiLine
2) Set up a connection to the database.
3) Set up an SQL command to read the numbers.
4) Clear the TextBox content.
5) Read the data from the DataBase and add each line to the TextBox.

An example of this is below, but bear in mind it will not work for you: your database and tables will be named differently, and you will need to get numbers and convert them to strings, instead of a string field called "message":
string strConnect = @"Database=SMLogging;Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=SMLogging;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    con.InfoMessage += new SqlInfoMessageEventHandler(con_InfoMessage);
    SqlDataReader r;
    using (SqlCommand com = new SqlCommand("SELECT * FROM SMAdmin.Log", con))
        {
        r = com.ExecuteReader();
        }
    List<string> lines = new List<string>();
    while (r.Read())
        {
        lines.Add((string) r["message"]);
        }
    myTextBox.Lines = lines.ToArray();
    }


SqlCommand comando = new SqlCommand();
string myConnectionString = "Data Source=SERVER_NAME;Initial Catalog=DATABASE_NAME;Persist Security Info=True;User ID=USER_NAME; Password=USER_PASSWORD";
SqlConnection conn = new SqlConnection(myConnectionString);
comando.Connection = conn;
comando.CommandText = "SELECT COUNT(*) FROM TABELA";
conn.Open();
TextBox1.Text = comando.ExecuteScalar().ToString();
conn.Close();





ai vaiasoluçãoparafunçõesqueretornam apenas um valor。

从谷歌翻译器翻译(不确定) - 为只返回一个值的函数提供解决方案。



ai vai a solução para funções que retornam apenas um valor.
Translated from Google Translator (not sure)- there goes solution for functions that return only one value.


这篇关于如何使用C#.net将数据从sql数据库显示到文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆