【问题标题】:GridView RowDataBound Handler - Can't get data from rowGridView RowDataBound 处理程序 - 无法从行中获取数据
【发布时间】:2011-07-19 01:05:44
【问题描述】:

我有一个匿名类型的 GridView。如果满足条件,我需要检查单元格中的值并突出显示该单元格。问题是,当我尝试从行的单元格中提取数据时,我总是得到一个空字符串。我已成功突出显示所有单元格,并在 Visual Studio 2010 调试器中检查并确认该行有数据(该行的 DataItem 具有我需要的值)。这发生在 PostBack 上,我不确定这是否有问题。

这是我尝试过的代码和解决方案:

protected void grvValidCourses_RowDataBound(Object sender, GridViewRowEventArgs e) {
 if (e.Row.RowType == DataControlRowType.DataRow) {
  String str = e.Row.Cells[6].Text.ToString(); // empty string
  Label lbl = (Label) grvValidCourses.FindControl("lblEndDate"); // null
  DataRowView rowView = (DataRowView)e.Row.DataItem; // exception about casting anonymous type

这里发生了什么?为什么我无法从单元格中获取数据?

GridView 的标记:

 <asp:GridView ID="grvValidCourses" runat="server" Width="790px" OnRowCancelingEdit="grvValidCourses_RowCancelingEdit"
                    OnRowEditing="grvValidCourses_RowEditing" OnRowUpdating="grvValidCourses_RowUpdating" OnRowDeleting="grvValidCourses_RowDeleting"
                    AutoGenerateColumns="False" OnSelectedIndexChanged="grvValidCourses_SelectedIndexChanged"
                    OnRowDataBound="grvValidCourses_RowDataBound" >
                    <Columns>
                        <asp:CommandField ShowEditButton="True" EditText="Edit" UpdateText="Update |" />
                        <asp:TemplateField ShowHeader="False">
                             <ItemTemplate>
                               <asp:LinkButton ID="lbnDelete" runat="server" CausesValidation="False" CommandName="Delete"
                                    Text='<%# (Eval("active") == null ? "Delete" : ((Eval("active").ToString() == "0" ? "Restore" : "Delete"))) %>' />  
                             </ItemTemplate>
                        </asp:TemplateField>
                        <asp:CommandField ShowSelectButton="True" SelectText="Details" />
                        <asp:TemplateField HeaderText="Training Name" SortExpression="coursename">
                            <EditItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Eval("coursename") %>'></asp:Label>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label2" runat="server" Text='<%# Bind("coursename") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="ttNo" HeaderText="#" SortExpression="ttNo" ReadOnly="True" />
                        <asp:TemplateField HeaderText="Course Date" SortExpression="startDate">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("startdate", "{0:M/d/yyyy}") %>'></asp:TextBox>
                                <asp:CalendarExtender ID="TextBox3_CalendarExtender" runat="server" Enabled="True"
                                    TargetControlID="TextBox3" Format="M/d/yyyy">
                                </asp:CalendarExtender>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label3" runat="server" Text='<%# Bind("startdate", "{0:M/d/yyyy}") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Expiry Date" SortExpression="endDate">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("enddate", "{0:M/d/yyy}") %>'></asp:TextBox>
                                <asp:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" Enabled="True"
                                    TargetControlID="TextBox1" Format="M/d/yyyy">
                                </asp:CalendarExtender>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="lblEndDate" runat="server" Text='<%# Bind("enddate", "{0:M/d/yyyy}") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <EmptyDataTemplate>No valid courses found.</EmptyDataTemplate>
                </asp:GridView>

更新:我一直在尝试您的所有建议,但我得到了异常、空值或空字符串。我什至在一个更简单的例子中重新创建了这个问题,但仍然无法弄清楚!不过我会继续努力,如果有任何新建议,我将不胜感激。

【问题讨论】:

    标签: c# .net asp.net gridview


    【解决方案1】:

    第 1 部分 - 缺少文本

    由于需要访问子控件,您可能在第一部分中得到空白值:

    String str = ((DataBoundLiteralControl)e.Row.Cells[6].Controls[0]).Text;
    

    查看您的单元格在调试模式下是否有任何值(检查调试输出窗口中的文本):

    void grvValidCourses_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        System.Diagnostics.Trace.WriteLine(e.Row.Cells.Count);
         foreach (TableCell c in e.Row.Cells)
         {
          System.Diagnostics.Trace.WriteLine(c.Text);
         }
      }
    }
    

    第 2 部分 - 缺少控制

    这是错误的:

    Label lbl = (Label) grvValidCourses.FindControl("lblEndDate"); // null
    

    您无法在 gridview 中搜索行的控件。您需要搜索该行。

    Label lblProductOptionGrpName = (Label)e.Row.FindControl("lblProductOptionGrpName");
    

    第 3 部分 - 访问 DataItem

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

    最后,我不确定您对匿名类型做了什么,但您可能需要在访问属性之前检查内容:

    if(MyControl.GetType() == typeof(HyperLink))
    {
      HyperLink TestLink = (HyperLink)MyControl;
      TestLink .Visible = false;
    }
    

    【讨论】:

    • 当我尝试第一行时,我在运行时遇到异常:无法将“System.Web.UI.LiteralControl”类型的对象转换为“System.Web.UI.DataBoundLiteralControl”类型。我尝试将其转换为 LiteralControl 并为 str 获得“/r/n”。不过,我会尝试您的其他建议。
    • 我尝试将调试器输出与您的第 1 部分建议一起使用,但我没有在输出中看到任何有用的信息(当然不是单元格值)。我尝试了您的第 2 部分,标签返回空白(文本为空字符串)。我不确定我是否真的理解你的第 3 部分。
    • protected void grvValidCourses_RowDataBound(Object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Label lbl = (Label)e.Row.FindControl("lblEndDate");字符串 str = lbl.Text;
    【解决方案2】:

    好的,我终于弄清楚发生了什么!我只能通过行访问绑定字段(例如e.Row.Cells[index].Text)。所以我使用绑定字段来获取我的项目的 ID,然后在数据库中找到该项目,获取日期,比较它,并突出显示该行的单元格。不是最有效的方法,但它确实有效。

    来自简单示例的代码:

    网格视图前端

    <asp:GridView ID="gdv" runat="server" AutoGenerateColumns="True" OnSelectedIndexChanged="gdv_SelectedIndexChanged">
            <Columns>
                <asp:CommandField ShowSelectButton="True" SelectText="Select" />
                <asp:BoundField DataField="id" HeaderText="#" ReadOnly="True" />
                <asp:TemplateField HeaderText="CategoryName" >
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Description" >
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("desc") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Label ID="lblSelected" runat="server" Text="No row selected"></asp:Label>
    

    页面背后的代码

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) {
            var qry = ctx.Categories
                  .Select(c => new {
                      id = c.CategoryID,
                      name = c.CategoryName,
                      desc = c.Description,
                  });
            gdv.DataSource = qry;
            gdv.DataBind();
        }
    }
    
    protected void gdv_SelectedIndexChanged(object sender, EventArgs e) {
        selectRow();
    }
    
    private void selectRow() {
        GridViewRow row = gdv.SelectedRow;
        String strId = row.Cells[1].Text; // Bound Field column
        lblSelected.Text = strId;
        // use ID to get object from database...
    }
    

    【讨论】:

      【解决方案3】:

      如果您可以发布标记,那么就有可能找出您的问题。

      你做错了,

      这个DataRowView rowView = (DataRowView)e.Row.DataItem;

      应该是DataRow rowView = ((DataRowView)e.Row.DataItem).Row;

      【讨论】:

      • 这给了我一个语法错误:错误 4 无法将类型“System.Data.DataRow”隐式转换为“System.Data.DataRowView”
      • 仍然出现无效的转换异常:无法转换类型为 'f__AnonymousType0`5[System.String,System.Nullable.... 的对象类型为 'System.Data.DataRowView
      【解决方案4】:
      protected void gridPanne_RowDataBound(object sender, GridViewRowEventArgs e)
      {
        if(e.Row.RowType==DataControlRowType.DataRow)
          {
              Label label = (Label)e.Row.FindControl("Label4");
              lbl.Text += "  ** / **  "+label.Text;
          }
      }
      

      【讨论】:

      • 您应该解释为什么/如何解决问题,而不是仅仅发布代码。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多