使用标签和工具提示动态绑定gridview

时间:2011-09-02 15:48:21

标签: c# asp.net gridview

我想在后面的代码中绑定gridview和datatable,我想在gridview中的每个单元格中添加标签,并在其值的标签上显示工具提示...我没有得到工具提示.. (我想展示那个舞台的每个座位)!!!并想要它的工具提示,以及我的舞台 可能会改变,所以我想动态地)

帮助我..我的代码在这里

//网格视图在页面加载时绑定 它给了我指数超出范围。必须是非负数且小于集合的大小。参数名称:index

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{


            for (int i = 0; i < table.Rows.Count; i++)
            {
                for (int j = 0; j < table.Columns.Count; j++)
                {


                    Label lbl = new Label();
                    lbl.Text = GridView1.DataKeys[e.Row.RowIndex]["LabelText"].ToString();
                    lbl.ToolTip = GridView1.DataKeys[e.Row.RowIndex]["TooltipText"].ToString();
                    e.Row.Cells[0].Controls.Add(lbl);

                }

            }

}

3 个答案:

答案 0 :(得分:1)

您需要将Label添加到GridView的每一行中的单元格。我建议将Label和工具提示的信息存储在数据密钥集合中,并在OnRowDataBound事件中添加标签。

选项1:

编辑:添加了标记以显示如何添加数据密钥

定义数据键,如下例所示。将LabelTextColumnTooltipTextColumn替换为您要用于文本和工具提示的实际值。另外,请注意如何在此处设置OnRowDataBound事件处理程序:

<asp:GridView ID="GridView1" runat="server" DataKeyNames="LabelTextColumn, TooltipTextColumn" OnRowDataBound="GridView1_RowDataBound" ...>
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        ...
    </Columns>
</asp:GridView>

编辑:使用RowIndex修正错误以获取数据密钥

由于您在RowDataBoundEvent中,因此不需要使用循环。从循环内调用RowDataBound事件,因为每行都是数据绑定,这就是您使用e.Row访问当前行的原因

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //we don't need this anymore, because the label is already in the row
    //Label lbl = new Label(); 

    //get the label from the row
    Label lbl = (Label)e.Row.FindControl("Label1");

    --set the text and tooltip text using the datakeys specified in the markup
    lbl.Text = grd.DataKeys[e.Row.RowIndex]["LabelTextColumn"].ToString();
    lbl.ToolTip = grd.DataKeys[e.Row.RowIndex]["TooltipTextColumn"].ToString();

    //we don't need this anymore either, because the label is already added to the row
    //e.Row.Cells[0].Controls.Add(lbl);
}

选项2:使用内联Eval()函数设置文本和工具提示文本

<asp:GridView ID="GridView1" runat="server"  ...>
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%#Eval("LabelTextColumn")' Tooltip='<%#Eval("TooltipTextColumn")%>' />
            </ItemTemplate>
        </asp:TemplateField>
        ...
    </Columns>
</asp:GridView>

答案 1 :(得分:0)

当您进行数据绑定时,它会销毁当前控件集合并使用提供的数据源进行填充。

对于您的特定应用程序,您还需要附加到GridView.RowCreated事件,然后插入所需的工具提示。

答案 2 :(得分:0)

Gridview.RowDataBound Event

的处理程序中实现此功能
相关问题