Question

I have check List like this

<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>

And I Am Trying To insert the Selected Values of CheckBoxlist into DB like this

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();
    }
}

When I Press the Button to Insert the the Values i got this error

Object reference not set to an instance of an object.

Please any One Guide me How To Insert the only selected Values of Check boxlist to DB.

Was it helpful?

Solution

You have created a new command, but not associated it with the adapter.

So, you need to add this to create the command within the adapter:

oda.InsertCommand = new OleDbCommand();

This will mean you can get rid of the line:

OleDbCommand cmd = new OleDbCommand();

OTHER TIPS

@Justin-Harvey right, But You not need DataAdapter (It is designed to mediate Database-DataSet). Here is your code without 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();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top