Web Forms DataGrid and DataSet Programming

Selecting a Row

One common task is to provide a button or link to "select" a row. The .NET DataGrid has built in event handling for many common button events. If you wish to add a custom button, you need to implement the OnItemCommand event handler to trap your custom button event. The ItemCommand event is fired for every button in the DataGrid. Although not very object oriented, you need to trap your custom event in the OnItemCommand event handler by switching on the Button's "CommandName". You set the custom button's CommandName in the HTML view.

Setting the CommandName in the HTML View

To set the CommandName, open the WebForm1.aspx in the HTML view. Here is the code that creates the DataGrid and sets the custom button "Select" CommandName:

<asp:datagrid id=DataGrid1 style="Z-INDEX: 101; LEFT: 23px; POSITION: absolute; TOP: 221px" runat="server"
DataKeyField="au_id" DataSource="<%# view %>" Height="270px" Width="679px"
OnUpdateCommand="DataGrid1_Update" OnCancelCommand="DataGrid1_Cancel" OnEditCommand="DataGrid1_Edit"
OnDeleteCommand="DataGrid1_Delete" BorderColor="Blue" OnItemCommand="Item_Click" AllowSorting="True"
OnSortCommand="DataGrid1_Sort" AllowPaging="True" OnPageIndexChanged="DataGrid1_Page" BackColor="#C0FFFF">
    <AlternatingItemStyle BackColor="White"></AlternatingItemStyle>
    <HeaderStyle BackColor="Wheat"></HeaderStyle>
        <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel" EditText="Edit">
        <asp:ButtonColumn Text="Delete" CommandName="Delete"></asp:ButtonColumn>
        <asp:ButtonColumn Text="Select" CommandName="SelectItem"></asp:ButtonColumn>

I have highlighted the line of server side HTML code that sets the CommandName and enables the OnItemCommand event handler.

Trapping the Custom Button Event

To trap the custom button event, you need to tell the DataGrid to enable the OnItemCommand handler. Again, this is done in the HTML view by adding the following to the asp:datagrid tag:


In your code behind page, add the "Item_Click" event handler. Here is the custom button event handler from the file WebForm1.aspx.cs

protected void Item_Click(Object sender, DataGridCommandEventArgs e)
    if (((LinkButton)e.CommandSource).CommandName == "SelectItem")
        string key = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
        string debug= "";
        // Fills text boxes with data in row
        // TextBox.Text Setter converts " to " Cool!
            DataRow dr= dataSet11.authors.FindByau_id(key);
            textBoxID.Text= dr["au_id"].ToString().TrimEnd(' ');
            textBoxLast.Text= dr["au_lname"].ToString().TrimEnd(' ');
            textBoxFirst.Text= dr["au_fname"].ToString().TrimEnd(' ');
            textBoxAddress.Text= dr["address"].ToString().TrimEnd(' ');
            textBoxCity.Text= dr["city"].ToString().TrimEnd(' ');
            textBoxState.Text= dr["state"].ToString().TrimEnd(' ');
            textBoxPhone.Text= dr["phone"].ToString().TrimEnd(' ');
            textBoxZip.Text= dr["zip"].ToString().TrimEnd(' ');
            textBoxContract.Text= dr["contract"].ToString().TrimEnd(' ');
        catch (Exception exc)
            debug= exc.Message;
        textBoxMessage.Text= debug;

In this sample, the CommandName is extracted form the DataGridCommandEventArgs by casting from e.CommandSource to a LinkButton. The call e.CommandSource returns a reference to an object. If all of the sources are of the type LinkButton this should be a valid cast. The LinkButton is then used to extract the CommandName. If the event was fired by the custom "Select" button, the data in the selected row is simply loaded from the DataSet into the appropriate text box. Of course, the function could just as easily save the information to a shopping cart or manipulate the data in the DataSet.

The Index in DataGrid and DataSet May Be Incongruent

It is important to note that the row index in the DataGrid and in the DataSet Table may not be congruent. To retrieve the correct row in the DataSet, you extract the primary key of the selected row in the DataGrid by calling:

string key = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();

(The DataKey property has been set to "au_id" in the <asp:datagrid> tag.) Now you can retrieve the row from the DataSet by calling:

DataRow dr= dataSet11.authors.FindByau_id(key);

Of course, there is no need to do this if you simply want extract the data directly from the DataGrid.


I found a most interesting bug in my original code. When I tried to filter after a "select", the code did not return any rows. It turns out that the data was padded with empty spaces! This confused my filtering logic. The workaround I used was to trim any trailing spaces before writing the data to the text boxes.

One nice feature that I note is the automatic HTMLEncoding performed by TextBox.Text. If you look at the actual HTML output in your browser you will note that quotes are converted to &qout; for proper display in the text box.

You might also like...



Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Every language has an optimization operator. In C++ that operator is ‘//’”