Visible false of button in gridview while data binding? In Asp.net? - asp.net

In web application, I am going to disable the button while binding data, is it possible visibling false like this?
<asp:Button ID ="btn" runat ="server" CommandArgument='<%# Eval("id").ToString() == "1"? visble false: Visible true %>' />

Try this:
<asp:Button ID="Button1" runat="server" Text="Button" Visible='<%#getVisibility()%>' OnClick="btn_Click" />
Code Behind:
public Boolean getVisibility()
{
Boolean b = false;
//get the boolean value based on your field condition
b = Convert.ToBoolean(Eval("FieldValue").ToString() != "MatchCondition" ? "true" : "false");
return b;
}

Do it in the DataGrid RowDataBound event

Either do that in the data bound event or do it like this...
<asp:Button ID ="btn" runat ="server" Visible='<%# Eval("id").ToString() == "1"? "false" : "true" %>' />

Related

Passing CommandArguement to LinkButton from variable

I have seen many resources on SO that say that I can use following syntax to pass value to CommandArguement of `LinkButton'
<%forearch(var comment in Comments){%>
<asp:LinkButton ID="del" CommandArguement='<%= comment.CommentId%>' onCommand="delete_click" Text="Delete"/>
<%}%>
But when I write this in my ascx file and click on the link the value passed to command argument is "<%=comment.CommentId%>" instead of commentId itself. Please guide what am I doing wrong?
Edit 1
based on answers and comments, I have moved to use repeater instead of foreach and plain code. Here is the code I have come up with
<asp:Repeater ID="commRepeater" SelectMethod="GetPageComments" runat="server">
<ItemTemplate>
<p>
<%#Eval("Comment") %>
<%if(Page.User.Identity.IsAuthenticated && Page.User.Identity.GetUserId() == Eval("UserId")){ %>
<span>
<asp:LinkButton Text="Edit" runat="server" ID="EditLink" CommandArgument='<%#Eval("CommentId")%>' OnClick="Update_Comment" />
<asp:LinkButton Text="Delete" runat="server" ID="DeleteLink" CommandArgument='<%#Eval("CommentId")%>' OnClientClick="if (!confirm('Are you sure you want delete?')) return false;" OnCommand="Delete_Comment" />
</span>
<%} %>
</p>
</ItemTemplate> </asp:Repeater>
you can see that I am trying to show the edit and delete links if user is logged in and his Id matches with user who commented but it tells me that I can on use Eval in databound controls. how would I hide/show edit/delete links conditionally within repeater
You could simply use codebehind, for example in Page_Load:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
del.CommandArgument = comment.CommentId;
}
}
Maybe a better approach would be to use the Comments-collection(which seems to be a list or array of a custom class) as DataSource of a Repeater(or other web-databound control). Then you can add the LinkButtons to the Itemtemplate.
You can then either use ItemCreated or ItemDataBound events of the repeater in codebehind or inline ASP.NET tags to bind the CommandArgument.
For example:
CommandArguement='<%# DataBinder.Eval( Container.DataItem, "CommentId" ) %>'
What you are doing currently is not recommended and is highly error prone. You can easily achieve this with ASP.NET Repeater control like this:-
<asp:Repeater ID="MyRepeater" runat="server">
<ItemTemplate>
<asp:LinkButton ID="del" CommandArguement='<%# Eval("CommentId") %>'
OnCommand="del_Command" Text="Delete" runat="server" />
</ItemTemplate>
</asp:Repeater>
In Page_Load simply bind it:-
if (!Page.IsPostBack)
{
MyRepeater.DataSource = CommentsRepository();
MyRepeater.DataBind();
}
Or Else if you are have ASP.NET 4.5 then use strongly type Data Bound controls like this:-
<asp:Repeater ID="MyRepeater" runat="server" ItemType="MyNamespace.Comment"
SelectMethod="MyRepeater_GetData">
<ItemTemplate>
<asp:LinkButton ID="del" CommandArguement='<%# Item.CommentId %>'
OnCommand="del_Command" Text="Delete" runat="server" />
</ItemTemplate>
</asp:Repeater>
And you method in code behind should be something like this(just for Demo):-
public IEnumerable<MyNamespace.Comment> MyRepeater_GetData()
{
return new List<Comment>
{
new Comment { CommentId =1, Name= "foo"},
new Comment { CommentId =2, Name= "bar"},
};
}

how to bind a value of datasource to a checkbox in datalist with Eval()

I have a datalist in my asp.net page. I bind a datasource to it in codebehind
and I have a checkbox in this datalist.
var n = from gi in DataContext.Context.GalleryImages
join g in DataContext.Context.Galleries
on gi.GalleryID equals g.GalleryID
where g.UserID == UserID && gi.GalleryID==GalleryID
select new
{
GalleryID = g.GalleryID,
ImageDescription = gi.ImageDescription,
GalleryName = g.GalleryName,
ImageFileName = gi.ImageFileName,
IsAlbumImage = gi.IsAlbumImage,
ImageID=gi.ImageID
};
dlGalleryList.DataSource = n;
dlGalleryList.DataBind();
When the "IsAlbumImage " is true the checkbox should be checked.
How can I bind this property to the checkbox?
It should be bind like:
<ItemTemplate>
<asp:CheckBox id="MyCheckBox" runat="server" Checked='<%#Eval("IsAlbumImage") %>' />
</ItemTemplate>
Actually you have to ways to bind checkbox in a datalist
1- (recommended) Binding it directly from the ASP code using the Bind or Eval
<ItemTemplate>
<asp:CheckBox id="MyCheckBox" runat="server" Checked='<%#Eval("IsAlbumImage") %>' />
</ItemTemplate>
2- Binding it on the ItemDataBound Event
First you will add the event handler to your datalist control, and adds the Boolean value to a datakey to be used in itemdatabound event
<asp:DataList ID = "DataList1" OnItemDataBound="DataListItemEventHandler" DataKeys = "IsAlbumImage"/>
Then you add the C# code that bind this
protected void DataListItemEventHandler(object sender, DataListItemEventArgs e)
{
CheckBox checkbx = new CheckBox();
checkbx = (CheckBox)e.Item.FindControl("MyCheckBox");
checkbx.Checked = (bool) DataList1.DataKeys(e.Item.ItemIndex)("IsAlbumImage");
}
Like this:
<asp:CheckBox
ID="check"
runat="server"
Checked='<%# Eval("column_name").ToString().Equals("1") %>'
/>

Make checkbox of detailsview to be checked by default for insert new record?

I am using DetailsView which its DefaultMode: insert, and I want to make its checkbox to be checked by default also user can change it to unchecked, but to bind checkbox we should use
Checked='<%# Bind("Cit_Visible") %>'
and this lets the default status of checkbox to be unchecked, so how can I solve this?
You can assign value to text property of checkbox if you want your check box selected at the time of data binding.
<asp:CheckBox ID="chl" runat="Server" Checked="true" Text="<%# Bind('Cit_Visible') %>" />
on code behind you can access text value to save it to in DB
CheckBox MyCheckbox = new CheckBox();
MyCheckbox = (CheckBox)DetailsView1.FindControl("chl");
Response.Write(MyCheckbox.Checked);
When using a DetailsView data control and you have checkbox values you may be starting with an asp:CheckBoxField which handles all the display modes for you. If you want to keep the checkbox binding but also set the default to checked perhaps for an insert you can do the following.
Convert the field to a TemplateField which can be done through the design view of visual studio or manually by replacing this type of block..
<asp:CheckBoxField DataField="Information" HeaderText="Information" SortExpression="Information" />
with a block of code like this
<asp:TemplateField HeaderText="Information" SortExpression="Information">
<EditItemTemplate>
<asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' />
</EditItemTemplate>
<InsertItemTemplate>
<asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' />
</InsertItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
Then to set the checkbox default value to be checked you can do this in the code-behind
Protected Sub dvInformation_PreRender(sender As Object, e As EventArgs) Handles dvInformation.PreRender
If CType(sender, DetailsView).CurrentMode = DetailsViewMode.Insert Then
Dim chk As Object = CType(sender, DetailsView).FindControl("chkInformation")
If chk IsNot Nothing AndAlso chk.GetType Is GetType(CheckBox) Then
CType(chk, CheckBox).Checked = True
End If
End If
End Sub
C# (Converted from VB
protected void dvInformation_PreRender(object sender, EventArgs e)
{
if (((DetailsView)sender).CurrentMode == DetailsViewMode.Insert) {
object chk = ((DetailsView)sender).FindControl("chkInformation");
if (chk != null && object.ReferenceEquals(chk.GetType(), typeof(CheckBox))) {
((CheckBox)chk).Checked = true;
}
}
}
This is obviously best when the supporting database value is a non-null bit field
Use TemplateField:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk1" runat="server" OnInit="chk1_Init" Checked='<%# Bind("Cit_Visible") %>' />
</ItemTemplate>
</asp:TemplateField>
Set the checkbox default value in the Init method:
protected void chk1_Init(object sender, EventArgs e)
{
((CheckBox)sender).Checked = true;
}

populate lable control inside a gridview based on inline Conditional statement

I am trying to display a plain text in the column(contains a label) of gridview based on a condition. Here is my erroneous code. Please correct.
<asp:Label ID="lblAsgn" runat="server" Text= '<%#Eval("StatusId") == 0 ? "NEW" : "OLD" %>' > </asp:Label>
Thanks in advance.
BB
<asp:Label
ID="lblAsgn"
runat="server"
Text='<%# FormatText(Eval("StatusId")) %>' />
where FormatText could be a method in your code behind:
protected string FormatText(object o)
{
int value;
if (int.Parse(o as string, out value) && value == 0)
{
return "NEW";
}
return "OLD";
}
Try this :
<asp:Label ID="lblAsgn" runat="server" Text= '<%# Eval("StatusId").Equals(0) ? "NEW" : "OLD" %>' > </asp:Label>

gridview dynamic image change in imagebutton

I have a gridview containing some data from db, and after a check I want to see a small cross/tick image in each row, due to the result of the check.How can I change the image url dynamically?
You could either use inline statement like
<%#Eval("check").ToString() == "1" ? "images/checked.gif" : "images/unchceked.gif")%>
or use a function to get the result as follows:
<%# getImageUrl(Eval("value")) %>
Public Function getImageUrl(ByVal value As Integer) As String
If value = 0 Then
Return "images/unchceked.gif"
Else
Return "mages/checked.gif"
End If
End Function
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="check" runat="server" ImageUrl='<%#If(Eval("check") = 1,"images/checked.gif","images/unchceked.gif") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
in form:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="check" runat="server" ImageUrl='<%# GetImageUrl(Eval("Check")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
code-behind:
public string GetImageUrl(object checkObject)
{
if (checkObject!= null)
{
bool check;
bool parsable = bool.Parse(checkObject.ToString(), out check);
check= parsable ? check : false;
return check ? "~/Media/Images/tick.png" : "~/Media/Images/untick.png";
}
return "~/Media/Images/none.png";
}

Resources