Library tutorials & articles

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>
    <Columns>
        <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel" EditText="Edit">
</asp:EditCommandColumn>
        <asp:ButtonColumn Text="Delete" CommandName="Delete"></asp:ButtonColumn>
        <asp:ButtonColumn Text="Select" CommandName="SelectItem"></asp:ButtonColumn>
    </Columns>
</asp:datagrid>

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:

OnItemCommand="Item_Click"

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!
        try
        {
            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.

Notes

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.

Comments

  1. 26 Jan 2006 at 14:50
    How could i do all this with untyped dataset from xml source? (no find methods etc..)
    Vjero
  2. 23 Nov 2005 at 14:26

    hi
    hey ppl i m   inserting some data manually in a dataview then i m sorting that dta via dataview.sort , sorting is taking place perfectly here but when i embed this data into a word document  then  i found that data is not  in sorted order as this supposed to be but it is in order in which it had typed...........so guys if u  have have any solution of this problem  then plz  mail me at aman_105@rediffmail.com

  3. 10 Nov 2005 at 09:33

    hello
     I am converting C#.net code into vb.net code .
     Sorting ASC or DESC  is not working .
     while degugging ,code work fine but i think some how dataset is not getting refreshed.
     I have commented these line  'view.RowFilter = lastFilter' .Is it require for sorting
     Execpt that everything is same
      please help me out .
                                                Thanks            
     

  4. 30 Jun 2005 at 02:13

    Hi.


    I dont know if this only a problem of mine, but when I hit a sort column the DataGridSortCommand happens twice.


    Should this happen? In my case it happens and so all the code in that event doesnt work properly...


    Could some help me out on this one?


    TIA,
    C.C.

  5. 10 Nov 2004 at 09:24
    How do I obtain ResetPageIndex? It is unknown to my installation of .NET or at least to the libraries I am using.
  6. 01 May 2004 at 12:13

    Jeff,


    Thanks a bunch!  I am new to ASP.NET programming and it was having a devil of a time getting my datagrid to sort -- your example provided the one missing link: the DataSource property should have been set to the view and not the dataset! Tanx again.


    --Babak

  7. 01 Jan 1999 at 00:00

    This thread is for discussions of Web Forms DataGrid and DataSet Programming.

Leave a comment

Sign in or Join us (it's free).

Jeff Louie
AddThis

Related podcasts

Events coming up

  • Nov 18

    15 Minutes of Fame

    Dresher, United States

    This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.

Want to stay in touch with what's going on? Follow us on twitter!