Team -

This has to be way more simple that I am getting. Been searching google for hours with no luck.

Simply stated, I am trying to delete a datalist row which is bound to a mssql database. Simple right!

I am missing where it is putting the key or something because I get getting the error "Object reference not set to an instance of object". I can't figure out how to give it the object!

Page code has the datakey:

<asp:DataList ID="DataList1" runat="server" DataKeyField="cartid" 
        DataSourceID="SqlDataSource1" Width="698px">

Code behind has the code from msdn:

Dim aTable As DataTable
        aTable = CType(DataList1.DataSource, DataTable)
        aTable.Rows(e.Item.ItemIndex).Delete()
        
        'reference from here http://msdn.microsoft.com/en-us/library/b7y72882(v=vs.71).aspx

But still getting the error. I am guessing the key isn't getting passed.

I am using asp.net (VB, with Visual Studio 2010, .net 3.5)

Thanks for helping!

Dewayne

Dani AI

Generated

— the NullReference comes from trying to cast a DataList control to a DataTable at a time when the control does not actually hold the bound DataTable. When you use a DataSource control (DataSourceID) or rely on normal data binding, the control does not keep a populated DataTable on the DataSource property between postbacks, so casting there will often be Nothing. Use the item-level key or the command argument instead of trying to pull a DataTable out of the control. (learn.microsoft.com)

A simple, reliable pattern: put a server button/link in the ItemTemplate that carries the row key, handle ItemCommand (or the DeleteCommand) on the DataList, then run a parameterized DELETE and rebind. Example (VB):

' ItemTemplate: CommandArgument='<%# Eval("cartid") %>' CommandName="DeleteItem"

Protected Sub DataList1_ItemCommand(sender As Object, e As DataListCommandEventArgs) Handles DataList1.ItemCommand
    If e.CommandName = "DeleteItem" Then
        Dim id As Integer = Convert.ToInt32(e.CommandArgument)
        Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConn").ConnectionString)
            Using cmd As New SqlCommand("DELETE FROM Cart WHERE cartid = @id", cn)
                cmd.Parameters.AddWithValue("@id", id)
                cn.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Using
        DataList1.DataBind()
    End If
End Sub

Troubleshooting tips: confirm the delete button has runat="server" and a nonempty CommandArgument, debug-print e.CommandArgument or use DataList1.DataKeys(e.Item.ItemIndex) (set DataKeyField) to verify the key, and always use parameters to avoid SQL injection. If you prefer declarative deletes you can also set a SqlDataSource DeleteCommand and call its Delete method from the command handler — either approach avoids casting the DataList.DataSource. (flylib.com)

I don't know VB so I'm tying in C#.

try using DataGrid control, It's easier.

//In Source
<asp:DataGrid ID="myd" runat="server" DataKeyField="StudentID" onDeleteCommand="delete">
 <Columns>
   <asp:ButtonColumn ButtonType="PushButton" Text="Delete"/>
 </Columns>

//In Code Behind Page Model
    SqlConnection sqlcon = new SqlConnection("Server=DEEPZ; uid=sa; pwd= ; database=student");
     protected void Page_Load(object sender, EventArgs e)
     {
        if (!IsPostBack)
        {
            BindGrid(); //user defined 
        }
    }
    public void delete(object sender, DataGridCommandEventArgs e)
    {
        sqlcon.Open();
        myd.Columns[0].HeaderText = "Delete";

        string del = "delete from Student where StudentID=@StudentID";
        SqlCommand cmddel = new SqlCommand(del, sqlcon);

        cmddel.Parameters.Add(new SqlParameter("@StudentID", SqlDbType.Int));
        cmddel.Parameters["@StudentID"].Value = myd.DataKeys[(int)e.Item.ItemIndex];

        try
        {
            cmddel.ExecuteNonQuery();
            Response.Write("<font color=blue> Record(s) Deleted! </font>");

        }
        catch (SqlException)
        {
            Response.Write("<font color=red> Deleting Failed! </font>");

        }
        sqlcon.Close();
        BindGrid();
    }

    public void BindGrid()
    {
        sqlcon.Open();
        SqlDataAdapter sqladap = new SqlDataAdapter("select * from Student",sqlcon);
        DataSet dset = new DataSet();
        sqladap.Fill(dset,"Student");
        myd.DataSource = dset.Tables["Student"].DefaultView;
        myd.DataBind();
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.