我正在创建一个预订管理系统,尝试从SQL数据库获取数据并将其插入到我的应用程序的一组文本框中时遇到问题。
我想在DataGridView中显示单击按钮时的客户详细信息,但是当我单击按钮时,应用程序将引发异常,并显示以下错误消息;
没有数据时,读取尝试无效。
我已经附上了要在其中查看客户详细信息的屏幕截图以及该按钮的代码,这些代码最终将在相应的文本框中显示客户详细信息。任何帮助将不胜感激!
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();
该行在reader.Read()您的代码中丢失。您应该添加它。它实际上是从数据库读取数据的功能:
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(); }
编辑: 假设您想将最后一条记录写入文本框,此代码将起作用。如果要应用不同的方案,例如单击Next按钮时从数据库读取所有记录并更改texbox中的数据,则应创建并使用自己的模型,也可以将数据存储在DataTable和如果需要,请稍后再参考。
Next