ASP.Net DataList Update command using C#

Updated on 08 Aug 2012,
Published on 14 Apr 2009

Update Command of ASP.Net DataList control provides you the functionality to save the changes done in the values of textbox controls placed inside the EditItemTemplate into the database table. In this tutorial we will use C# code to update the data items that will execute when user will hit the update link button. In the previous tutorial ASP.Net DataList EditItemTemplate we placed two link buttons inside the EditItemTemlate as a Cancel link and Update link. From the previous tutorial you can get the C# code for DataList Cancel Command in which CommandName property of Cancel link button was set as "cancel" that raises the OnCancelCommand event. Here you need to set the value of CommandName property equal to "update" that will execute the OnUpdateCommand C# code for updating the edited data items.

You can use the HTML code for DataList Control that we created in the tutorial ASP.Net DataList EditItemTemplate. When you will click on Edit link button it will render the items placed inside the EditItemTemplate hiding the ItemTemplate. You will get one textbox control associated with ProductName column, one read only UnitPrice field and two link buttons Update and Cancel.

Adding Update Command Event for DataList Control

To add Update Command event handler for DataList control. Follow the steps given below:

1. Copy and paste the same HTML code in the source view of ASP.Net web page that we designed in the previous tutorial ASP.Net DataList EditItemTemplate.

Note: If you are following the series of DataList control then you may already have added the DataList Edit command using C# and DataList Cancel command using C# that we learn in the previous tutorials.

2. Change the web page view mode to design view and then click on DataList control to select it.

3. Press F4 to open the properties window for getting the list of DataList control properties.

4. Click the events button of properties window to change its view that will provide the list of DataList events.

5. Then double click on UpdateCommand event to generate the OnUpdateCommand event handler in the C# code behind file to add the update command logic there.

Above figure show the Update command event attached to the DataList Control.

C# code for DataList Update Command

protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
    // Get the DataKey value associated with current Item Index.
    int ProductID = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
    
    // Get updated value entered by user in textbox control for 
    // ProductName field.
    TextBox txtProductName;
    txtProductName = (TextBox)e.Item.FindControl("txtProductName");

    // string variable to store the connection string
    // retrieved from the connectionStrings section of web.config
    string connectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

    // sql connection object
    SqlConnection mySqlConnection = new SqlConnection(connectionString);

    // sql command object initialized with update command text
    SqlCommand mySqlCommand = new SqlCommand("update products set productname=@productname where productid=@productid", mySqlConnection);
    mySqlCommand.Parameters.Add("@productname", SqlDbType.VarChar).Value = txtProductName.Text;
    mySqlCommand.Parameters.Add("@productid", SqlDbType.Int).Value = ProductID;

    // check the connection state and open it accordingly.
    if (mySqlConnection.State == ConnectionState.Closed)
        mySqlConnection.Open();

    // execute sql update query
    mySqlCommand.ExecuteNonQuery();

    // check the connection state and close it accordingly.
    if (mySqlConnection.State == ConnectionState.Open)
        mySqlConnection.Close();

    // reset the DataList mode back to its initial state
    DataList1.EditItemIndex = -1;
    BindDataList();
}

When user will hit the update link button it will execute the above C# Update Command event code that will update the data in SQL Database table and will hide the EditItemTemplate and render the ItemTemplate of DataList control back again.

DataList1.DataKeys[e.Item.ItemIndex] will return the value of data field added as DataKeyField of DataList control that provides the unique key or Primary key value. You can use this key value to update the database table values associated to it.

In the above C# code (TextBox)e.Item.FindControl("txtProductName") is used to find the textbox control placed inside the EditItemTemplate of DataList control to retrieve the new value entered before clicking the Update link button. FindControl method accepts the string value as ID of the server control that is to accessed dynamically.

Next we will add the C# code for ASP.net DataList Delete command.

Note: You can get the databinding code for DataList control from ASP.Net 2.0 DataList DataBinding using C# tutorial.

6 Responses to "ASP.Net DataList Update command using C#"
michael
My edit button works fine, but my update and cancel buttons do not work, they seem to act like a "back" button. Debugging shows that my update and cancel methods are not being called, even though I have bound them in the properties as instructed above. What do I do???? - Stressed out
mantu
hi,

i am facing problem in update database.
as i am having data like

vl1 vl2 vl3
2 1
3 2
4 3

i want to update table and put value in v3 as

vl1 vl2 vl3
2 1
3 2 1
4 3 2

pls help me out by giving code

mantu
Ezineasp.net
Hi Mantu Is this any sequential number series that you are trying to update into the database. Coz, it seems like the following expressions: (v|1) (v|1) - 1 (v|1) - 2 OR (v|1) (v|1) - 1 (v|2) - 1 You can use the variable values according to any of the above expression to update the three columns you have defined. Otherwise please explain in detail what you are trying to do?
ruchika
Hi,

When I click on edit button... I get a blank page.. all data gets lost... don't know why

Please help
ram
My edit button works fine, but my update and cancel buttons are working,but nothing is update? when i gave some value in edit option that is not updating .. it is coming previous value only . is there any change in code any body help me out. thanks
Alok
The Products table has a column named ProductName and a primary key column namedProductID. When a user selects an item in the DataList, you want to retrieve the value of the ProductID column associated with it.
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers