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

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.