簡體   English   中英

在 RowDataBound 事件上從網格視圖中獲取單元格的值

[英]Getting value from a cell from a gridview on RowDataBound event

string percentage = e.Row.Cells[7].Text;

我試圖用我的 GridView 做一些動態的事情,所以我已經將一些代碼連接到 RowDataBound 事件。 我正在嘗試從特定單元格獲取值,該單元格是 TemplateField。 但是上面的代碼似乎總是返回一個空字符串。

有任何想法嗎?

澄清一下,這里有一點有問題的單元格:

<asp:TemplateField HeaderText="# Percentage click throughs">
<ItemTemplate>
    <%# AddPercentClickThroughs((int)Eval("EmailSummary.pLinksClicked"), (int)Eval("NumberOfSends")) %>
</ItemTemplate>
</asp:TemplateField>

在相關說明中,有沒有人知道是否有更好的方法來選擇行中的單元格。 放入cell[1]很糟糕。 我不能做cell["mycellname"] ,所以如果我決定改變我的單元格的順序,錯誤就不會出現?

為什么不直接從數據源中拉出數據。

DataBinder.Eval(e.Row.DataItem, "ColumnName")

當您使用 TemplateField 並將文字文本綁定到它時,asp.net 實際上會為您插入一個控件! 它被放入一個 DataBoundLiteralControl。 如果您查看獲取空文本的代碼行附近的調試器,您就會看到這一點。

因此,要在不更改模板以使用控件的情況下訪問信息,您可以這樣轉換:

string percentage = ((DataBoundLiteralControl)e.Row.Cells[7].Controls[0]).Text;

這會讓你得到你的文字!

以上是很好的建議,但您可以在網格視圖中獲取單元格的文本值,而無需將其包裝在文字或標簽控件中。 你只需要知道要連接什么事件。 在這種情況下,請改用 DataBound 事件,如下所示:

protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[0].Text.Contains("sometext"))
        {
            e.Row.Cells[0].Font.Bold = true;
        }
    }
}

運行調試器時,您將看到此方法中出現的文本。

首先,您需要將代碼包裝在LabelLiteral控件中,以便您可以正確引用它。 發生的事情是系統無法跟蹤它,因為沒有與文本相關的控件。 將其內容添加到視圖狀態是控件的責任。

您需要使用 gridView.FindControl("controlName"); 獲得該行的控制權。 從那里你可以得到它的屬性,包括Text

您還可以獲取相關行的 DataItem 屬性並將其轉換為適當的類型並直接提取信息。

只需使用循環來檢查 gridview 中的單元格,例如:

for (int i = 0; i < GridView2.Rows.Count; i++)
{
    string vr;
    vr = GridView2.Rows[i].Cells[4].Text; // here you go vr = the value of the cel
    if (vr  == "0") // you can check for anything
    {
        GridView2.Rows[i].Cells[4].Text = "Done";
        // you can format this cell 
    }
}

使用RowDataBound函數將數據與特定單元格綁定,並獲得控件使用(ASP Control Name like DropDownList) GridView.FindControl("Name of Control")

我有一個類似的問題,但通過稍微不同的方法找到了解決方案。 我沒有像 Chris 建議的那樣查找控件,而是首先更改了在 .aspx 頁面中指定字段的方式。 我沒有使用<asp:TemplateField ...>標記,而是將相關字段更改為使用<asp:BoundField ...> 然后,當我到達 RowDataBound 事件時,可以直接在單元格中訪問數據。

相關片段: 一、aspx頁面:

<asp:GridView ID="gvVarianceReport" runat="server" ... >
...Other fields...
    <asp:BoundField DataField="TotalExpected" 
     HeaderText="Total Expected <br />Filtration Events" 
     HtmlEncode="False" ItemStyle-HorizontalAlign="Left" 
     SortExpression="TotalExpected" />
...
</asp:Gridview>

然后在 RowDataBound 事件中,我可以直接訪問這些值:

protected void gvVarianceReport_Sorting(object sender, GridViewSortEventArgs e)
{
    if (e.Row.Cells[2].Text == "0")
    {
        e.Row.Cells[2].Text = "N/A";
        e.Row.Cells[3].Text = "N/A";
        e.Row.Cells[4].Text = "N/A";
    }
}

如果有人可以評論為什么這有效,我將不勝感激。 我不完全理解為什么沒有 BoundField 綁定后值不在單元格中,但您必須通過控件查找它。

Label lblSecret = ((Label)e.Row.FindControl("lblSecret"));
<asp:TemplateField HeaderText="# Percentage click throughs">
  <ItemTemplate>
    <%# AddPercentClickThroughs(Convert.ToDecimal(DataBinder.Eval(Container.DataItem, "EmailSummary.pLinksClicked")), Convert.ToDecimal(DataBinder.Eval(Container.DataItem, "NumberOfSends")))%>
  </ItemTemplate>
</asp:TemplateField>


public string AddPercentClickThroughs(decimal NumberOfSends, decimal EmailSummary.pLinksClicked)
{
    decimal OccupancyPercentage = 0;
    if (TotalNoOfRooms != 0 && RoomsOccupied != 0)
    {
        OccupancyPercentage = (Convert.ToDecimal(NumberOfSends) / Convert.ToDecimal(EmailSummary.pLinksClicked) * 100);
    }
    return OccupancyPercentage.ToString("F");
}

如果將 asp:BoundField 上的屬性Visible設置為False 像這樣

<asp:BoundField DataField="F1" HeaderText="F1" Visible="False"/>

當您循環行時,您將不會在 Cells[i].Text 屬性中獲得任何文本。 所以

foreach (GridViewRow row in myGrid.Rows)
{
  userList.Add(row.Cells[0].Text); //this will be empty ""
}

但是您可以通過將網格連接到事件 OnRowDataBound 來設置不可見的列,然后從這里執行此操作

e.Row.Cells[0].Visible = false //now the cell has Text but it's hidden

關於列的索引選擇樣式,我建議您執行以下操作。 我遇到了這個問題,但我打算使用API動態設置值,所以我所做的是:記住.CastTo<T>只是((T)e.Row.DataItem)

並且您必須調用DataBind()才能查看網格中的更改。 這樣,如果您決定向網格添加一列,就不會遇到問題。

 protected void gvdata_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if(e.Row.RowType == DataControlRowType.DataRow)
            {
                var number = e.Row.DataItem.CastTo<DataRowView>().Row["number"];
                e.Row.DataItem.CastTo<DataRowView>().Row["ActivationDate"] = DateTime.Parse(userData.basic_info.creation_date).ToShortDateString();
                e.Row.DataItem.CastTo<DataRowView>().Row["ExpirationDate"] = DateTime.Parse(userData.basic_info.nearest_exp_date).ToShortDateString();
                e.Row.DataItem.CastTo<DataRowView>().Row["Remainder"] = Convert.ToDecimal(userData.basic_info.credit).ToStringWithSeparator();

                e.Row.DataBind();
            }
        }
protected void gvbind_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';";
        e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
        e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvbind, "Select$" + e.Row.RowIndex);
    }
}

暫無
暫無

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

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