簡體   English   中英

在C#中等同於VB.NET中的“句柄”

[英]Equivalent in C# to “Handles” in VB.NET

我在Visual Basic中有此代碼,並且在測試時可以工作。 所有行都有備用顏色。

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

由於我在C#環境下工作,因此將其轉換為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);
    }
}

這樣可以與Visual Basic中的“句柄”選項一樣嗎? 如果可能,請提供代碼。

您需要通過標記添加事件處理程序

<asp:GridView OnRowCreated="GridView1_RowCreated" runat="server" ID="MyGrid">

</asp:GridView>

或來自代碼隱藏

protected void Page_Load(object sender, EventArgs e)
{
   MyGrid.RowCreated += GridView1_RowCreated;
}

您必須像這樣在Page_Load()中添加處理程序:

Protected Void Page_Load(Object Sender, EventArgs e){
    GridView1.RowCreated += GridView1_RowCreated;
}

您可以嘗試

GridView1.RowCreated += GridView1_RowCreated;

注意:建議您在Page_Init (最佳實踐)中初始化您的委托

C#作為一種語言沒有像“ handles”關鍵字這樣的概念。 相反,您必須顯式連接事件定義。

嘗試

protected void Page_Load(object sender, EventArgs e)
{
    GridView1.RowCreated += GridView1_RowCreated;
}

C#通過'+ ='運算符添加處理程序,並通過'-='運算符將其刪除。

即使在VB.NET中,如果使用AutoEventWireUp =“ true”,也可以跳過“句柄”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM