0

我有这样的检查列表

<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 的选定值插入数据库

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.

请任何人指导我如何将复选框列表的唯一选定值插入数据库。

4

2 回答 2

1

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

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

oda.InsertCommand = new OleDbCommand();

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

OleDbCommand cmd = new OleDbCommand();
于 2013-10-10T09:22:28.017 回答
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();
    }
}
于 2013-10-10T09:29:08.703 回答