嗨,我是编程新手,目前正在从事一个项目,该项目允许用户使用文本框将其注册数据输入本地数据库。该代码的工作原理是将项目添加到数据库中,并且在我按下“Show_users”按钮后,它会将它们显示在 listBox_users 列表框中。
我的问题是,当我从 listBox_users 中选择一个名称时,它应该在上部 textBox'es 中显示有关所选用户的数据,我曾经使用我为 listBox_users 创建的事件首先输入数据,但我得到一个“无法从已关闭的数据库中读取数据”的错误。
namespace Userform
{
public partial class Form1: Form
{
SqlCeDataReader rdr;
public Form1()
{
InitializeComponent();
}
// Some code between...
private void button_ShowUsers_Click(object sender, EventArgs e) //code that shows users in listBox
{
var dt = new DataTable();
string connectionString2 = @"Data Source=MyDatabase;Password=xxxxxx;";
using (var cn = new SqlCeConnection(connectionString2))
using (var cmd = new SqlCeCommand("Select * From Users", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
var results = (from row in dt.AsEnumerable()
select new
{
//UserID = row.Field<int>("ID"),
FirstName = row.Field<string>("Firsname"),
LastName = row.Field<string>("Lastname"),
FullName = row.Field<string>("Firstname") + " " + row.Field<string>("Lastname")
}).ToList();
listBox_users.DataSource = results;
listBox_users.DisplayMember = "FullName";
rdr = cmd.ExecuteReader();
}
}
}
//I made an event for the listBox_users:
private void listBox_users_SelectedIndexChanged(object sender, EventArgs e)
//event code that should show listbox selected data in the textBoxes
{
if (listBox_inimesed.SelectedItem != null && rdr != null)
{
try
{
if (rdr.Read())
{
textBox1_firstname.Text = rdr.GetString(1);
textBox2_lastname.Text = rdr.GetString(2);
textBox3_email.Text = rdr.GetString(3);
textBox4_address.Text = rdr.GetString(4);
dateTimePicker1.Value = rdr.GetDateTime(5);
richTextBox_info.Text = rdr.GetString(6);
}
else MessageBox.Show("Object not found");
}
finally
{
rdr.Close();
}
}
}
}