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

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);

Related

Getting value from textbox in gridview

I have a GridView on which I am binding 2 textbox and a update button. grid view is dynamic so Row numbers can vary depending upon the size of dataset. Now what I want is when I change values in this textbox and click on update then data for that row in database should get updated. The textbox values in database should get updated.
This is my code:
<asp:GridView ID="dgAbstractSummary" runat="server" AutoGenerateColumns="False" OnRowDataBound="dgAbstractSummary_RowDataBound" OnRowCreated="dgAbstractSummary_RowCreated"
Visible="true">
<Columns>
<asp:BoundField HeaderText="ID" DataField="id" HtmlEncode="false"></asp:BoundField>
<asp:BoundField HeaderText="Abstract Title" DataField="title" HtmlEncode="false"></asp:BoundField>
<asp:TemplateField HeaderText="Significance Score">
<ItemTemplate>
<asp:TextBox ID="txtSignificanceScore" AutoPostBack="true" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"significanceScore")%>'></asp:TextBox>
<div class="voffset3"></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Innovation Score">
<ItemTemplate>
<asp:TextBox ID="txtInnovationScore" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"innovationScore")%>'></asp:TextBox>
<div class="voffset3"></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button AutoPostBack="true" CssClass="btn btn-primary btn-embossed" ID="btnUpdate" runat="server"
Text="Update"
OnClick="btnUpdate_Click" CommandArgument='<%#Eval("Id") %>' />
<div class="voffset3"></div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="panel-default"></HeaderStyle>
<RowStyle CssClass=""></RowStyle>
</asp:GridView>
C#
dgAbstractSummary.DataSource = dsResult; // dataset contains values which I am binding to grid columns
dgAbstractSummary.DataBind();
protected void btnUpdate_Click(object sender, EventArgs e)
{
Button myUpdateButton = (Button)sender;
}
Here Id (first column) is the unique key for each row.
Use find control function to find the two text boxes on the grid view row using your buttons sender event.
Something like this.
Button btn = (Button)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
TextBox details = gvr.FindControl("detailsText") as TextBox;
//do something with details
TextBox cusID = gvr.FindControl("TextBox2") as TextBox;

How to put each cell value for each row from GridView in variables

I tried some ways in stackoverflow solutions. But Those are not implemented well by me. Most of the time I got null/empty for the variables and Exception like "Object reference not set to an instance of an object."
My GridView:
<asp:GridView runat="server" ID="TestReportGridView" AutoGenerateColumns="false" Width="370px">
<Columns>
<asp:TemplateField HeaderText="ID" Visible="false">
<ItemTemplate>
<%#Eval("TestId") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sr">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Test">
<ItemTemplate>
<%#Eval("TestName") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Fee">
<ItemTemplate>
<%#Eval("Fee") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle HorizontalAlign="Left" />
</asp:GridView>
I want to put cell text in 4 different variables for each row when I click in Save button:
protected void SaveButton_Click(object sender, EventArgs e)
{
string patient = PatientNameTextBox.Text;
string birthDate = BirthDateTextBox.Text;
string mobile = MobileNoTextBox.Text;
int rows = TestReportGridView.Rows.Count;
foreach (GridViewRow row in TestReportGridView.Rows)
{
Label test = (Label)row.FindControl("Test");
string testName = test.Text;
//Label lblQuantity = (Label)row.FindControl("Quantity");
//string Quantity = lblQuantity.Text;
}
}
Image of the UI
I added a label in ItemTemplate. does it right way to add Label
<asp:TemplateField HeaderText="Test">
<ItemTemplate>
<asp:Label ID="Test" runat="server" ><%#Eval("TestName") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
You need to add Label control in your ItemTemplate. An example below:
<ItemTemplate>
<asp:Label ID="Test" runat="server" Text='<%# Eval("TestName") %>' />
</ItemTemplate>
Adding <%#Eval("TestId") %> directly inside ItemTemplate will not automatically add any control to search from code behind.

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.

Enabling And Disabling Buttons In GridView

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>

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