Enabling And Disabling Buttons In GridView - c#

I have added a button column to a gridview. I am populating the gridview with a datable through code then binding the datable to the grid.
I need to now look at the first column of the data and check if the text of the column is "NA" if it is the button in that column has to be disabled.....
How can I accomplish this? I am populating the data from code and the button is preadded to the grid in the markup
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:ButtonField Text="Delete" />
</Columns>
</asp:GridView>
GridView1.DataSource = dt;
GridView1.DataBind();

The best thing to do is implement the OnDataBinding method for a Button in a TemplateColumn.
Eg:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="btnDelete" CommandName="Delete"
Text="Delete" OnDataBinding="btnDelete_DataBinding" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in your codebehind implement your logic:
protected void btnDelete_DataBinding(object sender, System.EventArgs e)
{
Button btn = (Button)(sender);
btn.Enabled = !Eval("TheFieldInYourDataSourceToCompare").ToString().Equals("NA");
}
The advantage to doing it in this manner over the other posted answers:
No code in your markup
Code is localized to the Button control and can be reused if other Buttons require the same functionality.
Comparing to the DataSource value and not what the visual output is (this could tie into business logic for both rendering and checking).
Hope that helps.

Try this in the DataBound event handler:
protected void GridView1_DataBound(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.Rows[i].Cells[1].Text == "NA")
{
// Disable the button
}
}
}
This is just a general idea. You'll have to modify the code for your application.
Don't forget to add OnDataBound="GridView1_DataBound" to the markup for the GridView.

Maybe something like this.
Did the button a little differently
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="Btn_Delete" CommandName="Delete" Text="delete"
Enabled='<%# GridView1.Rows[0].Cells[1].Text != "NA" %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You'll want to you Eval("someColumn") most likely instead of GridView1.Rows[0].Cells[1].Text

Perhaps you can use OnRowDataBound="GridViewRowEventHandler" to set the value to enabled or disabled?

you can try from markup as,
<asp:TemplateField HeaderText="QA signature">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Column6") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Column6") %>' Visible='<%# Eval("Column6") != "" %>' ></asp:Label>
<asp:Button ID="Button2" runat="server" Text="Sign Off" CssClass="cmdButton" Visible='<%# Eval("Column6") == "" %>' />
</ItemTemplate>
</asp:TemplateField>

Related

How to get the Id from Gridview of Chechbox.checked?

I have GridView and a button as follows. Then i am binding the gridview with data from my database. GridView has two hiddenfield for Id and ClassIndex.
when i selecting a checkbox and click button, i want to get the corresponding Id and FileName.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="check" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdfId" runat ="server" Value='<%#Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdfClssIndex" runat ="server" Value='<%#Eval("ClassIndex") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblFileName" runat ="server" Text='<%#Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and Button Like
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Send Request" />
the code behind button is
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var check = row.FindControl("check") as CheckBox;
if (check.Checked)
{
int Id = Convert.ToInt32(row.Cells[1].Text);
//some logic follws here
}
}
}
but i am getting an error like
Input string was not in a correct format.
What is the error and how to solve it?
Your looping correct.
But you forgot to notice one thing here, when you wanted to access CheckBox you did a FindControl on row. Which means you are trying to find some control in that row.
Then why are you accessing HiddenField control inside row with row.Cell[1].Text?
Try to find that also.
int Id = Convert.ToInt32(((HiddenField)row.FindControl("hdfId")).Value);

GridView Delete Confirm ButtonField

I want to delete a row form my gridview with confirm by javascript.
My gridview looks like:
<asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand">
<Columns>
<asp:ButtonField CommandName="delete" Text="Delete" />
</Columns>
</asp:GridView>
I already tried do with TempleField and it works, but the problem is getting the value of the select row to delete from database.
I tried like this:
<asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSave" runat="server" Text="Delete" OnClientClick="return confirm('Do you want to delete?')" CommandName="delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And tried get the value like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
int index = Convert.ToInt32(e.CommandArgument);
string id = GridView1.Rows[index].Cells[1].Text.ToString();
Response.Write(id);
}
}
But it throws a FormatException on
int index = Convert.ToInt32(e.CommandArgument);
Can somebody help me? Sorry but my English is bad.
You need to set the CommandArgument from the button tag
<asp:Button ID="btnSave" runat="server" Text="Delete" OnClientClick="return confirm('Do you want to delete?')" CommandName="delete" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
Here is more info on how to use CommandArgument

FindControl in gridview returns null

I am currently in a dilemma with my gridview not returning a label, which is within a detailsview...
My C# code is:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
// get pet number for when removing a pet from reservation
int numberSelected = -1;
String numbertxt = "-1";
GridView gv1 = (GridView)sender;
GridViewRow rvRow = gv1.Rows[gv1.SelectedRow.RowIndex];
Label numberLbl = (Label)rvRow.Cells[0].FindControl("lblNumber");
// find selected index, and get number in column 0
// label within GridView1 within dvReservation DetailsView
numbertxt = numberLbl.Text;
...
Gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="dsObjGet"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField InsertVisible="False" ShowHeader="False">
<AlternatingItemTemplate>
<asp:Label ID="lblNumber" runat="server"
Text='<%# Eval("NUMBER") %>' Visible="False"></asp:Label>
</AlternatingItemTemplate>
<ItemTemplate>
<asp:Label ID="lblNumber" runat="server"
Text='<%# Eval("NUMBER") %>' Visible="False"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<AlternatingItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("NAME") %>'>
</asp:Label>
</AlternatingItemTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("NAME") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField SelectText="Remove" ShowSelectButton="True"
CausesValidation="False">
<ControlStyle CssClass="link" />
</asp:CommandField>
</Columns>
</asp:GridView>
When I breakpoint
Label numberLbl = (Label)rvRow.Cells[0].FindControl("lblNumber");
the label comes out as null (numberLbl)...
The message returned from the exception is:
"Object reference not set to an instance of an object"
EDIT:
This seems to be resolved if I generate lblNumber in an external gridview (on the page) with Eval("NUMBER"), though I don't see why it doesn't work in the current GridView I was trying to work with, given that GridView1 is within a DetailsView.
You should not use the Cell Collection when using FindControl. Just use this
GridView gv1 = (GridView)sender;
GridViewRow rvRow = gv1.SelectedRow;
Label numberLbl = (Label)rvRow.FindControl("lblNumber");

make Row in gridview asp.net clickable?

I create gridview and remove the select button to make all row clickable but I want to redirect the user for selected item detail
Note: I remover the CommandField select Visible="False"
int rowCount = 0;
protected void gv_TasksProjectForUser_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//var taskID = gv_TasksProjectForUser.SelectedDataKey.Value;
e.Row.Attributes.Add("onclick", "location='TaskDetail.aspx?taskID=" + e.Row.RowIndex + "'");
e.Row.Attributes.Add("onmouseover", "JavaScript:this.style.cursor='pointer';");
}
rowCount++;
}
I have made this with Item Templates.
What you have to do is remove the property AutogenerateColums and add them manually with objects and item templates, on those add one that could be a button.
Later on the code Behind add a event to handle the button click, on that event you can do the response.redirect to another page.
<asp:GridView ID="userGrid" runat="server" CssClass="AdminGrid"
AllowPaging="True" AutoGenerateColumns="False" PageSize="11">
<Columns>
<asp:BoundField DataField="ApplicationId" Visible="False" />
<asp:BoundField DataField="UserName" Visible="False" />
<asp:TemplateField >
<HeaderTemplate>
<asp:Label ID="lblEmail" Text="E-Mail" runat="server" CssClass = "HeaderLabel" meta:resourcekey="lblEmail"></asp:Label>
<asp:ImageButton ID="imgSortEMail" runat="server" ImageUrl="~/Images/normal.gif" OnClick="SortGrid" CommandArgument="EMail" CssClass="SortButton" ToolTip="Click here to Order" />
</HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="lnkEMail" runat="server" CssClass="EmailLinkButton" Text='<%# FormatGridTextDisplay(DataBinder.Eval(Container.DataItem, "EMail")) %>' ToolTip='<%# DataBinder.Eval(Container.DataItem, "EMail") %>' NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "EMail","mailto:{0}") %>' ></asp:HyperLink>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="OverFlowLeftAligned" />
</asp:TemplateField>
<asp:TemplateField >
<HeaderTemplate>
<asp:Label ID="lblSalonUser" Text="Salon User" runat="server" CssClass = "HeaderLabel" meta:resourcekey="lblSalonUser"></asp:Label>
<asp:ImageButton ID="imgSortIsSalonUser" runat="server" ImageUrl="~/Images/normal.gif" OnClick="SortGrid" CommandArgument="IsSalonUser" CssClass="SortButton" ToolTip="Click here to Order" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSalonUser" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "IsSalonUser") %>' onclick="javascript:if (this.checked==true) this.checked=false; else this.checked=true;"/>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="CenterAligned" />
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Editar" CssClass="GridButton" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "UserName")%> ' OnClick="btnEdit_Click" meta:resourcekey="btnEdit"/>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="CenterAligned" />
</asp:TemplateField>
</Columns>
</asp:GridView>
There You can see that i add a few types of items template, the most important is the btnEdit, on that one there are 2 important properies, one is the CommandArgument where you send the values to redirect to the page and the other is the event OnClick that is the one that will handle the click for the button.
Protected void btnEdit_Click(Object sender , System.EventArgs e ){
Button clickedButton = (sender)Button;
String() argumentsSend = clickedButton.CommandArgument.ToString().Split("|");
String backParameters;
Response.Redirect(String.Concat("RedirectPage.aspx?user=", Server.UrlEncode(argumentsSend(0)), "&company=", Server.UrlEncode(argumentsSend(1)), True);
}
I took this code from VB and change it to c# with a compiler, it may have errors, but that's the idea.
A easyest way is to use a link button or an hipperlink on the template of the grid, that eay you may no need to go to the code file.

Select any particular data from the gridview and dislay it in the label

hai pupils
I am doing a project on online education. In my project i display the trainees/trainers in in a gridview. If i select any data from the gridview it has to be dispalyed in the label kept below. How can i do this?
Thanks in advance for those who answers.
Use asp:LinkButton to show data in each column. Set commandArgument as the data. set same comandname and handle rowcommand in gridview rowcommand event.
try the following:
in aspx page:
<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" runat="server">
<Columns>
<asp:TemplateField HeaderText="CategoryID">
<ItemTemplate>
<asp:LinkButton ID="lnkID" runat="server" CommandName="sel" CommandArgument='<%# DataBinder.Eval(Container,"DataItem.CategoryID") %>'
Text='<%# DataBinder.Eval(Container,"DataItem.CategoryID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CategoryName">
<ItemTemplate>
<asp:LinkButton ID="lnkName" runat="server" CommandName="sel" CommandArgument='<%# DataBinder.Eval(Container,"DataItem.CategoryName") %>'
Text='<%# DataBinder.Eval(Container,"DataItem.CategoryName") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblCat" runat="server"></asp:Label>
in aspx.cs page:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "sel")
{
lblCat.Text = e.CommandArgument;
}
}

Categories