我在基于组合框填充文本框时遇到问题,插入代码也不起作用。
应该发生的是,通过从 ComboBox 中选择一个客户,详细信息会显示在文本框中,我还可以通过 TextBoxes 将客户添加到 ComboBox,还有一个 DataGridView 根据我的 ComboBox 选择显示来自另一个表的相关信息但这不是现在的问题。
笔记:
我最近切换到 Visual Studio 2012,我认为这不是问题。
组合框异常:
System.Data.SqlServerCe.dll 中出现“System.Data.SqlServerCe.SqlCeException”类型的异常,但未在用户代码中处理。
保存按钮异常:
输入字符串的格式不正确。
关于保存按钮,CustomerID 是一个自动增量编号,所以我应该可以将它的 TextBox 留空,但是当我这样做时它不起作用。
表结构:
Customers
CustomerID [int] [PK] [AutoNumber]
Name [nvarchar]
Phone1 [int]
Phone2 [int]
Address [nvarchar]
Notes [ntext]
代码:
private void FillCombo()
{
string code = "SELECT CustomerID, Name FROM Customers";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
cBox1.DataSource = ds.Tables[0];
cBox1.DisplayMember = "Name";
cBox1.ValueMember = "CustomerID";
}
private void frmMain_Load(object sender, EventArgs e)
{
clsMain.con.Open();
FillCombo();
}
private void cBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string code = "SELECT * FROM Customers WHERE CustomerID='" + cBox1.Text + "'";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, clsMain.con);
SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
if (cBox1.SelectedIndex > 0)
{
txt1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
txt2.Text = ds.Tables[0].Rows[0]["Name"].ToString();
txt3.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
txt4.Text = ds.Tables[0].Rows[0]["Phone2"].ToString();
txt5.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txt6.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
}
}
private void stripSave_Click(object sender, EventArgs e)
{
string code = "INSERT INTO Customers VALUES (@CustomerID, @Name, @Phone1, @Phone2, @Address, @Notes)";
SqlCeCommand cmd = new SqlCeCommand(code, clsMain.con);
cmd.Parameters.AddWithValue("@CustomerID", (txt1.Text); //Tried Parse and Convert.
cmd.Parameters.AddWithValue("@Name", txt2.Text);
cmd.Parameters.AddWithValue("@Phone1", txt3.Text);
cmd.Parameters.AddWithValue("@Phone2", txt4.Text);
cmd.Parameters.AddWithValue("@Address", txt5.Text);
cmd.Parameters.AddWithValue("@Notes", txt6.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
对不起,如果它是一个长代码,但我认为这样更容易发现问题。