<asp:DataGrid id="dgContacts" runat="server" PageSize="15" AllowSorting="True" AllowPaging="True" onItemCommand="SelectContact" OnPageIndexChanged="dgContacts_Page" Font-Size="X-Small" BorderStyle="Solid" BorderWidth="1px" Width="545px" CellPadding="3" AutoGenerateColumns="False"> <HeaderStyle font-size="Smaller" font-bold="True" forecolor="White" backcolor="DarkGoldenrod"></HeaderStyle> <PagerStyle mode="NumericPages"></PagerStyle> <AlternatingItemStyle bordercolor="White" backcolor="Wheat"></AlternatingItemStyle> <Columns> <asp:ButtonColumn Text="<img src=images/contactinfo.gif border=0 width=16 height=16>" CommandName="Select"> <ItemStyle horizontalalign="Center" verticalalign="Middle"></ItemStyle> </asp:ButtonColumn> <asp:BoundColumn Visible="False" DataField="contact_id" HeaderText="ID"></asp:BoundColumn> <asp:BoundColumn DataField="first_name" HeaderText="First Name"></asp:BoundColumn> <asp:BoundColumn DataField="last_name" HeaderText="Last Name"></asp:BoundColumn> <asp:BoundColumn DataField="home_email" HeaderText="Home Email"></asp:BoundColumn> <asp:BoundColumn DataField="home_phone" HeaderText="Home Phone"></asp:BoundColumn> </Columns> </asp:DataGrid>
protected void SelectContact( Object src, DataGridCommandEventArgs e )
{
try
{
string item = e.Item.Cells [ 1 ].Text;
Response.Redirect("viewcontact.aspx?id=" + item);
}
catch (Exception ex) {}
}
|
Notice the OnItemCommand attribute in the opening DataGrid tag. This is the method that wil be called when the user selects a row in the datagrid. The user actually selects an item by clicking on the "ButtonColumn" in the grid. Notice how an image is embedded in this column. In the SelectContact method you can see how we are accessing the ID of the current record by using the hidden ID bound column. |