【问题标题】:Disable hyperlink if cell value null in gridview如果gridview中的单元格值为null,则禁用超链接
【发布时间】:2018-06-24 21:18:34
【问题描述】:

我有一个动态填充列的网格。我有一个名为 ID 的列,它将启用超链接,如果单元格值为 null 或为空,则需要禁用超链接。

例如: 如果单元格值返回 0 或该 ID 列的空值,那么我需要禁用该列中这些单元格的超链接。下面的代码成功添加了超链接,最重要的是我需要检查单元格中的null0 值。

代码:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
        {
            string strHeaderRow = GridView1.HeaderRow.Cells[i].Text;
            if (strHeaderRow == "ID")
            {
                string strMktURL = "http://www.address.com";
                HyperLink hlColumns = AddHyperLink(e.Row.Cells[i], strMktURL);
            }
        }
    }
}

protected HyperLink AddHyperLink(TableCell cell, string strURL)
{
    HyperLink hl = new HyperLink();
    hl.Text = cell.Text;
    hl.Font.Underline = true;
    hl.Target = "_blank";
    hl.NavigateUrl = strURL;
    hl.Attributes.Add("style", "color:Black;");
    cell.Controls.Add(hl);
    return hl;
}

请建议如何实现。

【问题讨论】:

  • 你的代码没有做什么你想要的?它现在做什么?目前尚不清楚您要问什么以及您想要实现什么(例如,“禁用”超链接,或者如果值为空白/空,则不将超链接放入该单元格?)。请编辑问题以使其更清楚。
  • @Rory - 更新了我的帖子。请看一看。

标签: c# asp.net .net gridview


【解决方案1】:

只需检查您的单元格值是否为null 或为空并且不要将其设为超链接。 另外,如果您不使用其返回值,我建议您将 AddHyperLink() 设为无效。

更新

TableCell 将其值存储到 string Text 属性中,因此:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string strMktURL = "http://www.address.com";
        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
        {
            string strHeaderRow = GridView1.HeaderRow.Cells[i].Text;
            if (strHeaderRow == "ID")
            {
                if(!string.IsNullOrEmpty(e.Row.Cells[i].Text))
                {
                    HyperLink hlColumns = AddHyperLink(e.Row.Cells[i], strMktURL);
                }
            }
        }
    }
}

【讨论】:

  • 它不起作用,我认为它与格式化有关。仅供参考,如果它是整数或小数,我该如何处理?
  • 所以integerdecimal?
  • 如果是intdecimal,则不能为空,只有null如果是Nullable
  • 它是一个整数。我在这一行出现错误(e.Row.Cells[i] as int?) 无法将类型 TableCell 转换为 int?通过参考转换。
  • 好的,我对 Gridview 没有任何经验,但是根据 MSDN,TableCell 将其值存储到 string Text 属性中,所以请查看更新的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 2020-02-01
  • 1970-01-01
  • 2015-02-01
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
相关资源
最近更新 更多