我正在尝试使用URL添加linkbutton到gridview小计行。我使用以下代码而无法添加网址。
有人可以提供有关如何处理此事的建议吗?
更新1:
private void AddTotalRow(string labelText, string value)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
row.Cells.AddRange(new TableCell[3] { new TableCell{ Text = labelText, HorizontalAlign = HorizontalAlign.Right },
new TableCell{ Text = value, HorizontalAlign = HorizontalAlign.Right },
HyperLinkCell(value, "http://www.google.com") });
}
protected TableCell HyperLinkCell(string text, string url)
{
TableCell cell = new TableCell();
HyperLink link = new HyperLink();
try
{
link.Text = text;
link.Font.Underline = true;
link.Target = "_blank";
link.NavigateUrl = url;
link.Attributes.Add("style", "color:Black;");
cell.Controls.Add(link);
}
catch (Exception ex)
{
throw ex;
}
return cell;
}
答案 0 :(得分:1)
您想要向表中添加新单元格。但您也尝试将LinkButton
添加到TableCell集合中。
同时在创建新的LinkButton时,您正在设置Text = AddHyperLink
。 AddHyperLink方法返回HyperLink对象,显然你不能分配给Text,因为它是一个字符串类型。
此外,您无法将LinkButton添加到TableCell集合。
您需要更改以下代码。
private void AddTotalRow(string labelText, string value)
{
GridViewRow row = new GridViewRow(0,0, DataControlwRowType.DataRow, DataControlRowState.Normal);
row.BackColor = ColorTranslator.FromHtml("#F9F9F9");
row.Cells.AddRange(new TableCell[4] { new TableCell(),
new TableCell{ Text = labelText, HorizontalAlign = HorizontalAlign.Right }.
new TableCell{ Text = value, HorizontalAlign = HorizontalAlign.Right),
//Calling HyperLinkCell method which will return a TableCell with HyperLink in it.
HyperLinkCell(value, "http://www.google.com")
});
gvData.Rows.Add(row);
}
protected TableCell (string text, string url)
{
//Create new Cell
TableCell cell = new TableCell();
//Create new HyperLink.
HyperLink link = new HyperLink();
try
{
link.Text = text;
link.Font.UnderLine = true;
link.Target = "_blank";
link.NavigationUrl = url;
link.Attributes.Add("style", "color:Black;");
//Add hyperlink to the cell.
cell.Controls.Add(link);
}
catch(Exception ex)
{
}
//Return Cell with HyperLink.
return cell;
}
这将解决错误,并为您提供在gridviewrow中添加带超链接的单元格的正确方法。
答案 1 :(得分:0)
尝试以下方法:
protected HyperLink AddHyperLink(string cell, string strURL)
{
HyperLink h1 = new HyperLink();
TableCell cells = new TableCell();
try
{
h1.Text = cell;
h1.Font.Underline = true;
h1.Target = "_blank";
h1.NavigateUrl = strURL;
h1.Attributes.Add("style", "color:black");
cells.Controls.Add(h1);
}
catch(Exception ex)
{
}
return h1;
}