messif
messif

Reputation: 92

Inserting data from ASP.Net form to a datatable

I know most of you will say google this. But I have already done that and still can't quite figure out why on button event click the data still won't be inserted into the data table. Ignore the data itself, it's random.

Any help would be greatly appreciated.

        public void btnAddRow_Click(object sender, EventArgs e)
    {
        DataSet ds = (DataSet)(Session["DS"]);
        TestGrid.DataSource = ds.Tables[0];
        ds.Tables[0].Rows.Add();

        DataTable dt = (DataTable)(Session["DT"]);
        DataRow dr = null;
        dr = dt.NewRow();



        //add values to each rows
        dr["Title"] = txtTitle.Text;
        dr["Year"] = txtYear.Text;
        dr["Type"] = txtType.Text;
        dr["Lead Actor"] = txtLeadActor.Text;
        dr["Producer"] = txtProducer.Text;
        dr["Director"] = txtDirector.Text;

        dt.Rows.Add(dr);
        TestGrid.DataSource = dt;
        TestGrid.DataBind();

    }

    private void SetInitialRow()
    {

        DataTable dt = new DataTable();
        DataRow dr = null;
        Session["DT"] = dt;

        //define the columns
        dt.Columns.Add(new DataColumn("Title", typeof(string)));
        dt.Columns.Add(new DataColumn("Year", typeof(string)));
        dt.Columns.Add(new DataColumn("Type", typeof(string)));
        dt.Columns.Add(new DataColumn("Lead Actor", typeof(string)));
        dt.Columns.Add(new DataColumn("Producer", typeof(string)));
        dt.Columns.Add(new DataColumn("Director", typeof(string)));


        //create new row
        dr = dt.NewRow();


        //add values to each rows
        dr["Title"] = "Blade";
        dr["Year"] = "1989";
        dr["Type"] = "Action";
        dr["Lead Actor"] = "Wesley Snipes";
        dr["Producer"] = "Guy";
        dr["Director"] = "Dude";


        //add the row to DataTable
        dt.Rows.Add(dr);
        TestGrid.DataSource = dt;
        TestGrid.DataBind();


    }

Upvotes: 0

Views: 6162

Answers (1)

iefpw
iefpw

Reputation: 7062

The code looks correct.

DataTable _table = new DataTable()
DataRow _row = _table.NewRow()
_table.Rows.Add(_row)

I think it might be your postback. Put a breakpoint after Rows.Add(_row) and make sure the datatable has the data. I think the data is getting deleted on postback/page load.

Upvotes: 1

Related Questions