我需要根据某些条件显示删除按钮。
ASPX:
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnDelete" runat="server" CommandName="Delete"
ImageUrl="~/Images/Delete.gif" Visible="false" />
</ItemTemplate>
</asp:TemplateField>
背后的代码:
protected void gvL3App_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataTable dtInactiveCodes = DataRepository.getInactiveCodes();
string[] strInactive = dtInactiveCodes.AsEnumerable()
.Select(row => row.Field<string>("Code")).ToArray();
foreach (var value in strInactive)
{
ImageButton btnDelete= (ImageButton)e.Row.FindControl("btnDelete");
btnDelete.Visible = true;
}
}
这里
dtInactiveCodes
数据表返回145
,248
,268
,478
等值。现在,gridview的第一列将包含这些数据表返回值。我需要检查这些值并显示删除。
但删除按钮对于所有行都是可见的,并且不适用于上述代码。
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:2)
您可以使用一个公共函数SetButtonVisibility
来接收"code"
或您要检查的列名。
ASPX:
<asp:TemplateField>
<ItemTemplate>
<!-- I have added a additional parent Div to contain the row style... You could use or replace this with some other element -->
<div class='<%# CssClassForRow(Eval("code").ToString()) %>'>
<asp:ImageButton ID="btnDelete" runat="server" CommandName="Delete"
ImageUrl="~/Images/Delete.gif" Visible='<%# SetButtonVisibility(Eval("code").ToString()) %>' />
</div>
</ItemTemplate>
</asp:TemplateField>
这里只是重复使用相同的逻辑来比较"code"
中是否存在此getInactiveCodes
并返回"true"
或"false"
。
代码背后:
public bool SetButtonVisibility(String codeValueOfRow)
{
if(GetMatchingCodeCount(codeValueOfRow) > 0) return true;
else return false;
}
public string CssClassForRow(String codeValueOfRow){
//your logic here to check which CssClass to apply
//If you want the logic to be same as above, then I suggest calling the same method.
if(GetMatchingCodeCount(codeValueOfRow) > 0) return "highlight";
else return "non_highlight";
//[OR]
//If you want to use some other logic... then...
//A simple sample logic would be...
if(someValue == "highlight") return "highlight";
else return "non_highlight";
}
//Creating this method, to avoid code repetition.
public int GetMatchingCodeCount(string codeValue) {
DataTable dtInactiveCodes = DataRepository.getInactiveCodes();
return dtInactiveCodes.AsEnumerable().Count(row => row.Field<string>("Code")==codeValue);
}
Css样式表:
.highlight {
background-color: #f00;/* Hexa-decimal color code for background*/
}
.non_highlight { /* No style here ... But you could add something here for the other rows, if you want*/ }
希望这有帮助。
答案 1 :(得分:0)
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl_firstCol = (Label)e.Row.FindControl("FirstCols");
if (lbl_firstCol.Text=="145" || lbl_firstCol.Text=="248" || lbl_firstCol.Text=="268" || lbl_firstCol.Text=="478")
{
ImageButton btnDelete= (ImageButton)e.Row.FindControl("btnDelete");
btnDelete.Visible = true;
}
}