如何使用 C# 从 SQL 数据库获取值到文本框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16565035/
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
How do I get values from a SQL database into textboxes using C#?
提问by Captain_Custard
I'm creating a booking management system and I am having problems trying to get data from a SQL database and insert into a group of textboxes of my application.
我正在创建一个预订管理系统,但在尝试从 SQL 数据库获取数据并将其插入到我的应用程序的一组文本框时遇到了问题。
I want to show the customer details, when a button is clicked, in a DataGridView, but when I click the button, the application throws an exception with the following error message;
我想在 DataGridView 中单击按钮时显示客户详细信息,但是当我单击按钮时,应用程序抛出异常并显示以下错误消息;
Invalid attempt to read when no data is present.
不存在数据时尝试读取无效。
I have attached a screenshotof the screen where I want to view customer details, and the code for the button, which will eventually show customer details in the respective textboxes. Any help would be greatly appreciated!
我附上了我想要查看客户详细信息的屏幕截图,以及按钮的代码,最终将在相应的文本框中显示客户详细信息。任何帮助将不胜感激!
SqlConnection sc = new SqlConnection("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True");
SqlCommand com = new SqlCommand();
com.Connection = sc;
sc.Open();
SqlDataReader read = (null);
com.CommandText = ("select * from Pending_Tasks");
read = com.ExecuteReader();
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
sc.Close();
采纳答案by Adil Mammadov
The line reader.Read()is missing in your code. You should add it. It is the function which actually reads data from the database:
reader.Read()您的代码中缺少该行。你应该添加它。它是实际从数据库读取数据的函数:
string conString = "Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "select * from Pending_Tasks";
SqlCommand com = new SqlCommand(selectSql, con);
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while(reader.Read())
{
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
}
}
}
finally
{
con.Close();
}
EDIT :This code works supposing you want to write the last record to your textboxes. If you want to apply a different scenario, like for example to read all the records from database and to change data in the texboxes when you click the Nextbutton, you should create and use your own Model, or you can store data in the DataTable and refer to them later if you wish.
编辑:假设您想将最后一条记录写入文本框,此代码有效。如果您想应用不同的场景,例如从数据库中读取所有记录并在单击Next按钮时更改 texbox 中的数据,您应该创建并使用自己的模型,或者您可以将数据存储在 DataTable 和如果您愿意,请稍后参考。
回答by David S.
read = com.ExecuteReader()
read = com.ExecuteReader()
SqlDataReaderhas a function Read()that reads the next row from your query's results and returns a boolwhether it found a next row to read or not. So you need to check that before you actually get the columns from your reader (which always just gets the current row that Read()got). Or preferably make a loop while(read.Read())if your query returns multiple rows.
SqlDataReader有一个函数Read()可以从查询结果中读取下一行并返回bool是否找到要读取的下一行。所以你需要在你真正从你的读者那里得到列之前检查一下(它总是只得到当前得到的行Read())。或者,while(read.Read())如果您的查询返回多行,最好进行循环。
回答by christiandev
using (SqlConnection connection = new SqlConnection("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True"))
{
SqlCommand command =
new SqlCommand("select * from Pending_Tasks WHERE CustomerId=...", connection);
connection.Open();
SqlDataReader read= command.ExecuteReader();
while (read.Read())
{
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();
}
Make sure you have data in the query : select * from Pending_Tasksand you are using "using System.Data.SqlClient;"
确保查询中有数据:select * from Pending_Tasks并且您正在使用“using System.Data.SqlClient;”
回答by Manoj Niakm
If you want to display single value access from database into textbox, please refer to the code below:
如果要将数据库中的单值访问显示到文本框中,请参考以下代码:
SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
TextBox1.Text=cmd.ExecuteScalar();
Con.Close();
or
或者
SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
SqlDataReader dr=new SqlDataReadr();
dr=cmd.Executereader();
if(dr.read())
{
TextBox1.Text=dr.GetValue(0).Tostring();
}
Con.Close();
回答by Kuharan Bhowmik
Make a connection and open it.
建立连接并打开它。
con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=<database_name>)));User Id =<userid>; Password =<password>");
con.Open();
Write the select query:
编写选择查询:
string sql = "select * from Pending_Tasks";
Create a command object:
创建命令对象:
OracleCommand cmd = new OracleCommand(sql, con);
Execute the command and put the result in a object to read it.
执行命令并将结果放入一个对象中以读取它。
OracleDataReader r = cmd.ExecuteReader();
now start reading from it.
现在开始阅读它。
while (read.Read())
{
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();
Add this too using Oracle.ManagedDataAccess.Client;
也使用Oracle.ManagedDataAccess.Client添加它;

