DataGrid Demo with a More Advanced Button Event Handler
This demo shows a DataGrid Web control with a Details "button" present and demonstrates how to
have a piece of code fire when a button is clicked. Note that after clicking the button you can
see information about the row that contained the button that was clicked.
Source Code
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script language="vb" runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack then
BindData()
End If
End Sub
Sub BindData()
'1. Create a connection
Dim myConnection as New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))
'2. Create the command object, passing in the SQL string
Const strSQL as String = "sp_Popularity"
Dim myCommand as New SqlCommand(strSQL, myConnection)
'Set the datagrid's datasource to the datareader and databind
myConnection.Open()
dgPopularFAQs.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
dgPopularFAQs.DataBind()
End Sub
Sub dispDetails(sender as Object, e As DataGridCommandEventArgs)
Dim buttonColumn as TableCell = e.Item.Cells(0)
Dim FAQIDColumn as TableCell = e.Item.Cells(1)
Dim DescColumn as TableCell = e.Item.Cells(2)
Dim buttonColText as String = buttonColumn.Text
Dim FAQIDColText as String = FAQIDColumn.Text
Dim DescColText as String = DescColumn.Text
lblBCT.Text = buttonColText
lblFCT.Text = FAQIDColText
lblDCT.Text = DescColText
End Sub
</script>
<form runat="server">
<b>Value of Clicked Button Column Text</b>:
<asp:label id="lblBCT" runat="server" /><br />
<b>Value of FAQID Column Text</b>:
<asp:label id="lblFCT" runat="server" /><br />
<b>Value of Clicked Description Column Text</b>:
<asp:label id="lblDCT" runat="server" /><br />
<asp:DataGrid runat="server" id="dgPopularFAQs"
BackColor="#eeeeee" Width="85%"
HorizontalAlign="Center"
Font-Name="Verdana" CellPadding="4"
Font-Size="10pt" AutoGenerateColumns="False"
OnItemCommand="dispDetails">
<HeaderStyle BackColor="Black" ForeColor="White" Font-Bold="True" HorizontalAlign="Center" />
<AlternatingItemStyle BackColor="White" />
<Columns>
<asp:ButtonColumn Text="Details" HeaderText="FAQ Details" CommandName="details" ButtonType="PushButton" />
<asp:BoundColumn DataField="FAQID" HeaderText="FAQ ID" />
<asp:BoundColumn DataField="Description" HeaderText="FAQ Description" />
</Columns>
</asp:datagrid>
</form>