我知道这是这里某些问题的重复,但相信我,我已经尝试了所有这些问题,但没有运气。
我是 C#+MySQL 的新手。
我有一个包含 2 个表、程序员和软件的数据库。我在软件表中有一个名为programmersid 的列。这是一对多的关系。我有两个列表框。第一个是程序员的名字,当我点击程序员时,它会显示他制作的软件。
当我点击一个软件时,文本将被放入一个文本框中,并且我有一个更新按钮。当我单击它时,它应该更新该软件的名称。
这是我的代码:
public partial class Form1 : Form
{
private DataSet ds;
private SqlConnection conn;
private SqlDataAdapter programmersadapter;
private SqlDataAdapter softwaresadapter;
protected string connectionString = "Data Source=ICEBOX19-PC\\ICEBOX;Initial Catalog=software;Integrated Security=True";
public Form1()
{
InitializeComponent();
conn = new SqlConnection(connectionString);
SqlCommand programmersselect = new SqlCommand("SELECT ID, Name FROM programmers", conn);
programmersadapter = new SqlDataAdapter(programmersselect);
SqlCommand softwaresselect = new SqlCommand("SELECT name FROM softwares WHERE programmerid = @ID", conn);
softwaresselect.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int));
softwaresadapter = new SqlDataAdapter(softwaresselect);
showme();
}
private void showme()
{
ds = new DataSet();
conn.Open();
programmersadapter.Fill(ds, "programmers");
conn.Close();
listBox1.ValueMember = "id";
listBox1.DisplayMember = "name";
listBox1.DataSource = ds.Tables["programmers"];
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand command = new SqlCommand("update softwares set name='" + textBox1.Text + "' where programmerid=" + listBox2.SelectedValue.ToString(), conn);
command.ExecuteNonQuery();
conn.Close();
reload();
}
private void reload()
{
//listBox2.SelectedIndexChanged -= listBox2_SelectedIndexChanged;
softwaresadapter.SelectCommand.Parameters["@id"].Value = listBox1.SelectedValue;
var table = new DataTable();
softwaresadapter.Fill(table);
conn.Close();
listBox2.DisplayMember = "name";
listBox2.ValueMember = "id";
listBox2.DataSource = table;
//listBox2.SelectedIndexChanged += listBox2_SelectedIndexChanged;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
reload();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = listBox2.Text;
textBox1.Text = textBox1.Text.Replace(" ", "");
}
}
我得到这个例外:
无法绑定多部分标识符“System.Data.DataRowView”。
它来自command.ExecuteNonQuery()
于button1.Click
.
我试图改变:
SqlCommand command = new SqlCommand("update softwares set name='" + textBox1.Text + "' where programmerid=" + listBox2.SelectedValue, conn);
至
SqlCommand command = new SqlCommand("update softwares set name='" + textBox1.Text + "' where programmerid=" + listBox2.SelectedValue.ToString(), conn);
但我也得到同样的东西。你们有什么想法吗?我从 2 小时开始就在寻找这个。
PS:即使我尝试删除,我也会收到同样的错误
private void delete_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand command = new SqlCommand("delete from softwares where id="+listBox2.SelectedItem, conn);
command.ExecuteNonQuery();
conn.Close();
}