Click here to Skip to main content
16,013,581 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey Guys,
following is the code for EditTemplete-UpdateCommand of a dataList Control(Datalist1), I am using Linq2Sql. The Sql Class name is Baby and I am using the datalist control to diplay the all the records from Baby table.
The problem is, that for updating how do I get the Itemindex of the record that is to be updated. I know the problem is only with one line in the following code that is "Baby bab = (Baby)e.Item.DataItem;" but I really don't know how to get it right

C#
protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
    TextBox txtName = (TextBox)e.Item.FindControl("txtName");
    TextBox txtDate = (TextBox)e.Item.FindControl("txtDate");
    TextBox txtTime = (TextBox)e.Item.FindControl("txtTime");
    TextBox txtParents = (TextBox)e.Item.FindControl("txtParents");
    TextBox txtWeight = (TextBox)e.Item.FindControl("txtWeight");
    TextBox txtLength = (TextBox)e.Item.FindControl("txtLength");

    Baby bab = (Baby)e.Item.DataItem;  ////Code with the problem
    bab.name = txtName.Text;
    bab.date = txtDate.Text;
    bab.time = txtTime.Text;
    bab.parents = txtParents.Text;
    bab.weight = txtWeight.Text;
    bab.length = txtLength.Text;
    bab.Save();
    DataList1.EditItemIndex = -1;
    DataBind();


Thank you for all the help.
Chetan.
Posted
Updated 30-Sep-10 7:50am
v2

1 solution

Use DataKeyField property of the DataList indicate primary key of your Baby object.

<asp:DataList ... DataKeyField="BabyPkId" ...

Retrieve the primary key from the datakeys

int pkId = (int)DataList1.DataKeys[(int)e.Item.ItemIndex];


Query your Linq2Sql datasource for the Baby entity matching the value in pkId, set the properties, and update.
 
Share this answer
 
Comments
cnjadhav 5-Oct-10 10:42am    
Thank you very much William,,,,that was great and worked well..!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900