I Like to add Image buttons in a Databound ASP.NET 4.0 GridView
for a Boolean field in a way that if it is true show one image and if it is false show another image.
ImageField
does not give me click ability and I don't know how to change image on buttons based on field value. With Button trigger I will run a stored procedure to change the state of Boolean field.
I'm using C# for programming
How can I achieve this?
Create a template field and place your image button in it.
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton runat="server" ID="myImageButton" />
</ItemTemplate>
</asp:TemplateField>
Then inside your RowDataBound
event check the condition and assign the image url
protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton myImageButton = e.Row.FindControl("myImageButton") as ImageButton;
if (myImageButton != null)
{
if (Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "myBooleanField")))
{
myImageButton.ImageUrl = "image1.jpg";
}
else
{
myImageButton.ImageUrl = "image2.jpg";
}
}
}
}
同样非常简单直接的解决方案是使用两个图像字段,并根据布尔值隐藏一个或另一个。
First of all use Template Field and place a ImageButton then assign a code Behind method to the ImageUrl attribute,this method will return the path of image based upon the 'Status'. Also make use of the CommandArgument attribute to store the Status, which can be used to update the 'Status' to the database when the button is clicked.
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton runat="server" ID="ImgBtnStatus" CommandArgument='<%# Eval("Status") %>' ImageUrl='<%# Bind_Image(Eval("Status").ToString()) %>' />
</ItemTemplate>
</asp:TemplateField>
Here we are calling a code behind method and it looks as shown below.
public string Bind_Image(string Status)
{
bool status = Convert.ToBoolean(Status);
// If Status is true , bind the img_true.bmp
if (status)
{
return "~/images/img_true.bmp";
}
else
{
return "~/images/img_false.bmp";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.