将checkboxlist值插入db

时间:2013-10-10 09:10:53

标签: c# nullreferenceexception checkboxlist

我检查了这样的列表

<asp:CheckBoxList ID="CA" runat="server" DataSourceID="SqlDataSource1" 
        DataTextField="MNU_NAME" DataValueField="MNU_ID">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:DataConnectionString2 %>" 
        ProviderName="<%$ ConnectionStrings:DataConnectionString2.ProviderName %>" 
        SelectCommand="SELECT ID, MNU_ID, MNU_NAME, MNU_TAB FROM MENU_LIST WHERE (MNU_TAB = 'CA')" 
    </InsertParameters>
</asp:SqlDataSource>

我正在尝试将CheckBoxlist的选定值插入到DB中

OleDbDataAdapter oda = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand();
if (TextBox1.Text == null || TextBox1.Text == "")
{
    Response.Write("Enter Email");
}
foreach (ListItem li in CA.Items)
{
    if (li.Selected == true)
    {
        oda.InsertCommand.CommandText = "INSERT INTO USR_MNU(LNK_NAME,USR_EMAIL,ACTIVE) values('" + li.Value + "','" + TextBox1.Text + "',1)";
        oda.InsertCommand.Connection = con;
        oda.InsertCommand.Connection.Open();
        oda.InsertCommand.ExecuteNonQuery();
        oda.InsertCommand.Connection.Close();
    }
}

当我按下按钮插入值时出现此错误

Object reference not set to an instance of an object.

请任何一位指南我如何将唯一选中的复选框值列表插入数据库。

2 个答案:

答案 0 :(得分:1)

您已创建新命令,但未将其与适配器关联。

因此,您需要添加此命令以在适配器中创建命令:

oda.InsertCommand = new OleDbCommand();

这意味着你可以摆脱这条线:

OleDbCommand cmd = new OleDbCommand();

答案 1 :(得分:0)

@ Justin-Harvey对, 但您不需要DataAdapter(它旨在调解Database-DataSet)。 这是没有DataAdapter的代码:

OleDbCommand cmd = new OleDbCommand();
if (TextBox1.Text == null || TextBox1.Text == "")
{
    Response.Write("Enter Email");
}
foreach (ListItem li in CA.Items)
{
    if (li.Selected == true)
    {
        cmd.CommandText = "INSERT INTO USR_MNU(LNK_NAME,USR_EMAIL,ACTIVE) values('" + li.Value + "','" + TextBox1.Text + "',1)";
        cmd.Connection = con;
        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        cmd.Connection.Close();
    }
}