Freigeben über


Handling events inside datagrid control

 This sample will give us an idea on: -

  1. How we can handle several events provided by Datagrid.
  2. How we can change behavior, L&F of Datagrid at runtime.

Note: - This sample uses pubs database.

 

First let’s define the Datagrid on the aspx page.

 

<asp:DataGrid ID="grid" Runat="server" AutoGenerateColumns="False"

DataKeyField="au_id" OnItemCreated="grid_OnItemCreated"

OnSelectedIndexChanged="grid_OnSelectedIndexChanged" OnItemDataBound="grid_OnItemDataBound"

OnItemCommand="grid_OnItemCommand"

OnEditCommand="grid_EditCommand"

OnUpdateCommand="grid_UpdateCommand"

OnCancelCommand="grid_CancelCommand"

>

                                               

            <HeaderStyle BackColor="#ffffcc" />

            <AlternatingItemStyle BackColor="#cccc99" />

            <EditItemStyle BackColor="#ccccff" />

            <FooterStyle BackColor="#ffccff" />

            <ItemStyle BackColor="#336699" />

            <SelectedItemStyle BackColor="#cc9966" />

            <Columns>

                        <asp:BoundColumn Runat="server" DataField="au_id"

HeaderText="AuthorID"></asp:BoundColumn>

                        <asp:BoundColumn Runat="server" DataField="au_lname"

HeaderText="Last Name"></asp:BoundColumn>

                        <asp:BoundColumn Runat="server" DataField="au_fname"

HeaderText="First Name"></asp:BoundColumn>

                        <asp:HyperLinkColumn Runat="server" DataTextField="address"

HeaderText="Address" DataNavigateUrlField="au_id"

DataNavigateUrlFormatString="EmployeeInfo.aspx?id={0}" Target="_search">

                        </asp:HyperLinkColumn>

           

                        <asp:TemplateColumn>

                                    <ItemTemplate>

                                    <asp:Label Runat=server ID=lblCity Text='<%#

DataBinder.Eval(Container.DataItem, "city") %>'>

</asp:Label>

                                    </ItemTemplate>

                                    <EditItemTemplate>

                                                <asp:TextBox ID=txtCity Runat=server Text='<%#

DataBinder.Eval(Container.DataItem, "city") %>'>

</asp:TextBox>

                                    </EditItemTemplate>

                        </asp:TemplateColumn>

                       

<asp:EditCommandColumn runat="server" EditText="Edit"

UpdateText="Update"

CancelText="Cancel">

</asp:EditCommandColumn>

            </Columns>

</asp:DataGrid>

 

 

Now we will define several events that are supported by Datagrid in the code behind.

 

First of all we need to bind the Datagrid in order to display the data. Datagrid is designed in such a way that it needs to be re-bound on each and every postback. Getting data repeatedly from the data source on every request leads to a poor performance. In this case, server side caching techniques can make a difference.

 

Best place to bind the data is inside Page_Load method.

protected string connectionString = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=pubs;Data Source=PARAGA1";

protected string cmdText = "select au_id,au_lname,au_fname,address,city from authors";

private void Page_Load(object sender, System.EventArgs e)

{

DataTable dataTable = FillDataTable();

grid.DataSource = dataTable;

grid.DataBind();

}

DataTable FillDataTable()

{

SqlDataAdapter sqlDA = new SqlDataAdapter(cmdText,connectionString);

      DataTable dataTable = new DataTable();

      sqlDA.Fill(dataTable);

      return dataTable;

}

Before we start defining more events provided by Datagrid first we need to know what the constituent elements of a Datagrid are. All these elements can either be data bound or they can have static text.

 

Header – It represents the grid’s header, which describes the columns inside the grid.

 

Footer – It represents the grid footer.

 

Item and Alternating Item – Represents rows inside the grid.

 

EditItem – Represents rows inside grid under editable mode.

 

Pager – If paging is enabled on grid it represents the pager element which can be used to scroll between pages.

 

SelectedItem – Represents currently selected row in the grid.

 

Let’s understand how data binding takes place.

 

Data-binding process for Datagrid takes place when DataBind method is called. This process can be best understood by a pseudo code.

 

Start DataBinding

  1. Call data bind event of parent class.
  2. Clear all the collection of child controls.
  3. Clear the view state.
  4. Build the Datagrid by creating the control hierarchy. (It is responsible for setting the hierarchy of controls and the resulting HTML (table). Here creation of various grid items takes place which we have discussed above. For each created item, set of events are fired ItemCreated and ItemDataBound .
  5. Start monitoring the view state for any change.

End DataBinding

Now let’s take a look at the various events that we can call on Datagrid.

 

/// <summary>

/// This event is called when ever a new DataGrid item is created.

/// it’s fired immediately after DatagridItem (Row) object is created

/// and before it is added to resulting HTML table.

/// Here we are getting one of the Items called Header and changing its

/// text at runtime.

/// </summary>

public void grid_OnItemCreated(object sender, DataGridItemEventArgs e)

{

      if (e.Item.ItemType == ListItemType.Header)

{

            TableCellCollection tcc = e.Item.Cells;

            for (int i=0; i<tcc.Count; i++)

            {

                  TableCell tc = e.Item.Cells[i];

                  tc.Text = "Any New Header Value" + i.ToString();

            }

      }

}

/// <summary>

/// This event is fired immediately after ItemCreated event if item

/// supports data binding.

/// Here we are accessing the Datagrid Items (rows) and changing the /// Tooltip of first columns inside that row.

/// </summary>

public void grid_OnItemDataBound(object sender, DataGridItemEventArgs e)

{

      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

      {

            DataRowView drv = (DataRowView)e.Item.DataItem;

            WebControl webCtrl = (WebControl)e.Item.Cells[0];

            webCtrl.ToolTip = "Tooltip value";

      }

}

/// <summary>

/// This event is fired when different Item (row) is selected

/// inside a grid.

/// </summary>

public void grid_OnSelectedIndexChanged(object sender, EventArgs e)

{

      // getting au_id which is a Data key field for grid.

int au_id = (int)grid.DataKeys[grid.SelectedIndex];

     

string clientScript = "<script language='javascript'>" + "window.alert('" + au_id.ToString() + "')</script>";

     

Response.Write (clientScript);

}

/// <summary>

/// This event is fired when any button (asp:ButtonColumn) is clicked /// inside a grid.

/// </summary>

public void grid_OnItemCommand(object sender, DataGridCommandEventArgs e)

{

      // e.CommandName specifies which button caused the postback.

      switch(e.CommandName)

      {

            case "Select" : string au_id =

grid.DataKeys[e.Item.ItemIndex].ToString();

            string clientScript = "<script

language='javascript'>" +

"window.alert('" + au_id + "')</script>";

                              Response.Write (clientScript);

                        break;

           

            default: Response.Write ("No action");

                              break;

      }

}

 

 

/// <summary>

/// This event is fired when edit command column

/// (asp:EditCommandColumn)is specified in the grid’s column collection /// and then user clicks on Edit button.

/// </summary>

public void grid_EditCommand(object source, DataGridCommandEventArgs e)

{

      // sets the current item in edit mode.

grid.EditItemIndex = e.Item.ItemIndex;

     

      // Rebinding the data to maintain grid state.

DataTable dataTable = FillDataTable(cmdText,connectionString);

      grid.DataSource = dataTable;

      grid.DataBind();

}

/// <summary>

/// This event is fired the user clicks on Update button under edit

/// mode.

/// </summary>

public void grid_UpdateCommand(object source, DataGridCommandEventArgs e)

{

      // Cancel the edit mode for the row.

      grid.EditItemIndex = -1;

     

      // e.Item represents the current row which we want to

// updated. This row represents collection of various

// columns.

TextBox txtCity = (TextBox)e.Item.FindControl("txtCity");

      string au_id = grid.DataKeys[e.Item.ItemIndex].ToString();

      // Updating the modified value for ‘txtCity’ column in the table.

string updateQry = "UPDATE authors SET City='" + txtCity.Text +

"' WHERE au_id='" + au_id + "'";

      SqlConnection cnn = new SqlConnection(connectionString);

      cnn.Open();

      SqlCommand cmd = new SqlCommand(updateQry,cnn);

      cmd.ExecuteNonQuery();

      cnn.Close();

      // Re-binding the Datagrid from the updated data source.

      DataTable dataTable = FillDataTable(cmdText,connectionString);

      grid.DataSource = dataTable;

      grid.DataBind();

}

public void grid_CancelCommand(object source, DataGridCommandEventArgs e)

{

// Cancel the edit mode for the row.

      grid.EditItemIndex = -1;

     

      // Refresh the grid.

DataTable dataTable = FillDataTable(cmdText,connectionString);

      grid.DataSource = dataTable;

      grid.DataBind();

}