I have this code in Visual Basic, and it works when I test it. All the rows have alternate colors.
Private Sub GridView1_RowCreated(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim RowNum as Integer
RowNum = e.Row.RowIndex
If RowNum mod 2 = 1 Then
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#DDDDDD'")
Else
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'")
End If
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='DeepSkyBlue'")
e.Row.Attributes("onclick") = Me.Page.ClientScript.GetPostBackClientHyperlink(Me.GridView1, "Select$" & e.Row.RowIndex)
End If
End Sub
Since I am working under C# enviroment, I converted it to C#:
private void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int RowNum = e.Row.RowIndex;
if (RowNum % 2 == 1)
{
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#DDDDDD'");
}
else
{
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
}
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='DeepSkyBlue'");
e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
Is that a way I can do same as "Handles" option in Visual Basic? Please provide me the code if possible.
You'll need to add the event handler either from markup
<asp:GridView OnRowCreated="GridView1_RowCreated" runat="server" ID="MyGrid">
</asp:GridView>
or from code-behind
protected void Page_Load(object sender, EventArgs e)
{
MyGrid.RowCreated += GridView1_RowCreated;
}
You have to add the handler in Page_Load() like this:
Protected Void Page_Load(Object Sender, EventArgs e){
GridView1.RowCreated += GridView1_RowCreated;
}
You can try with
GridView1.RowCreated += GridView1_RowCreated;
Nota : I suggest you to initialize your delegate in Page_Init
(Best Practise)
C# as a language doesn't have a concept like the "handles" keyword. Instead, you must explicitly wire-up event definitions.
Try
protected void Page_Load(object sender, EventArgs e)
{
GridView1.RowCreated += GridView1_RowCreated;
}
C# adds handlers by '+=' operator and remove them by '-=' operator.
Even in VB.NET you can skip "handles" if you use AutoEventWireUp="true".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.