【问题标题】:id getting inserted without selecting in c#.netid 被插入而不在 c#.net 中选择
【发布时间】:2014-01-16 14:04:36
【问题描述】:
private void Form1_Load(object sender, EventArgs e)
       {
        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
        con.Open();

        OleDbDataReader DR = cmd.ExecuteReader();
        DataTable table = new DataTable();
        table.Load(DR);
        combo_status.DataSource = table;
        combo_status.DisplayMember = "project_name";
        combo_status.ValueMember = "ID";
        combo_status.Text = "Select Project Name";
    }

private void btnSave_Click_Click(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection(constr);
        con.Open();
        OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (@name)", con);

        cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);

        cmd.ExecuteNonQuery();
        con.Close();
        MessageBox.Show("Inserted sucessfully");

    }

在第一个类中,我有一个组合框,我从数据库中获取它的值,并且我在组合框中的页面加载上显示了“选择项目名称”。我只想在用户从下拉列表中选择选项并且不插入任何内容时插入它的值如果用户没有选择任何选项。

现在的问题是,下拉菜单中的名字会在按钮单击时插入。没有选择任何选项。我希望如果用户没有从下拉菜单中选择任何名称值,则不应插入任何内容。

谁能帮帮我..?

【问题讨论】:

  • 因为默认情况下您的组合框 selectedindex 等于 0(如果您的数据源为空,则为 -1),因此如果您不想在用户没有从组合框中选择的情况下向数据库插入任何内容,您可以添加一个空行作为组合框的第一项,
  • 如何添加一个空行作为组合框的第一项你能告诉我吗??

标签: c#


【解决方案1】:

假设ID 列的数据类型是int:

private void Form1_Load(object sender, EventArgs e)
   {
    OleDbConnection con = new OleDbConnection(constr);
    OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
    con.Open();

    OleDbDataReader DR = cmd.ExecuteReader();
    DataTable table = new DataTable();
    table.Load(DR);

    //begin adding line
    DataRow row = table.NewRow();
    row["project_name"] = "Select Project Name";
    row["ID"] = 0;
    table.Rows.InsertAt(row, 0);
    //end adding line

    combo_status.DataSource = table;
    combo_status.DisplayMember = "project_name";
    combo_status.ValueMember = "ID";
    combo_status.Text = "Select Project Name";
}

private void btnSave_Click_Click(object sender, EventArgs e)
{
    if(combo_status.SelectedValue == 0)
    {
         return; //do nothing if user didn't select anything in combobox, you can change this line of code with whatever process you want
    }

    OleDbConnection con = new OleDbConnection(constr);
    con.Open();
    OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (@name)", con);

    cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);

    cmd.ExecuteNonQuery();
    con.Close();
    MessageBox.Show("Inserted sucessfully");

}

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多