Accessing grid view row data C# - c#

I am trying to set the value of a textbox to the value of a column in a gridview. I am getting the row from a LinkButton.
The first TextBox1.Text line below works correctly to set the value of the textbox to the row number.
The second TextBox1.Text line below does nothing to my textbox. I am expecting the value of the row(index) and column(1), but I get nothing. There is definitely data in the gridview. The gridview is 10+ columns wide, and I have checked the value from 0-5 and get nothing in the textbox.
I am not running it with both lines uncommented out at once.
I am doing all of this to troubleshoot an issue being caused by it.
protected void lnkbtnPassRowData_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
if (gvr != null)
{
int index = Convert.ToInt32(gvr.RowIndex.ToString());
TextBox1.Text = GridStaffMyJobs.Rows[index].RowIndex.ToString();
TextBox1.Text = GridStaffMyJobs.Rows[index].Cells[1].Text;
}
}
Here is the code from the gridview that contains the link button.
<form id="StaffMyJobs" runat="server">
<div>
<h3>My Jobs</h3>
</div>
<div>
<asp:Label ID="lblHired" runat="server" Text="Rows in green indicate jobs that have been filled." Visible="False" BorderColor="#FF0909" Font-Bold="True" Font-Underline="True" ForeColor="YellowGreen"></asp:Label>
<br />
<asp:Label ID="lblOffers" runat="server" Text="Rows in red indicate jobs that have pending offers." Visible="False" BorderColor="#FF0909" Font-Bold="True" Font-Underline="True" ForeColor="Red"></asp:Label>
<br />
<asp:Button ID="btnAddJob" runat="server" Text="Add a Job" OnClick="btnAddJob_Click" Visible="true" />
<br />
<br />
</div>
<div>
<asp:GridView ID="GridMoreJobs" runat="server" AutoGenerateColumns="False" DataSourceID="SQLMoreJobs" >
<Columns>
<asp:BoundField DataField="more_jobs" HeaderText="more_jobs" SortExpression="more_jobs" Visible="false" />
</Columns>
</asp:GridView>
</div>
<div>
<asp:GridView ID="GridStaffMyJobs" runat="server" AutoGenerateColumns ="False" DataSourceID="SQLStaffMyJobs" ShowFooter="True" OnRowDataBound="GridMoreJobs_RowDataBound" HorizontalAlign="Center" >
<Columns>
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnPassRowData" Text='Reopen'
runat="server"
OnClick="lnkbtnPassRowData_Click" Visible='<%#
CanReopen((object)Eval("student_hired")) %>' />
</ItemTemplate>
</asp:TemplateField>
</form>
Here is a screenshot of executing the page and letting the line run that puts the index of the row in the textbox.

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 correctly get cell value in gridview after clicking on a linkbutton inside a gridview and enable correct async postback to display a modal

I am making a reservation system and currently stuck on the following situation.
Basically I have a GridView which is loaded with the reservation ID and two LinkButton which opens a modal popup to enable the customer to view the details.
What I want to achieve is that when I click any LinkButton, it will show the ID from the first cell of a GridViewRow.
I have tried these methods here, here, here, and here but it still doesn't work. Is there any way to do it, Aside from using a SELECT Command and does involve async postback or if async postback is not possible with this, any fix recommended?
Here is my GridView code:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvReservationSummaries"/>
</Triggers>
<ContentTemplate>
<h2>Reservations</h2>
<br />
<asp:GridView ID="gvReservationSummaries" runat="server"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" ShowHeader="False" CellPadding="5" CellSpacing="5"
onrowcommand="Gridview1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"><%# Eval("Master_Reservation_ID")%></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="ViewReservationDetails" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'>View Reservation Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="ViewReceiptDetails" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'>View Receipt Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DB_9E4ABD_GratchiOBRSConnectionString2 %>"
SelectCommand="SELECT [Master_Reservation_ID] FROM [Master_Reservation] WHERE User_Unique_ID = #uuid">
<SelectParameters>
<asp:SessionParameter Name="uuid" SessionField="uid" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:Button ID="btnShowModal" runat="server" Text="Show Modal 1 (Debug Purposes Only)" onclick="btnShowModal_Click" />
<!--Here, put the details of the reservaton, plus options to edit reservation.-->
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
<asp:Panel ID="reservationSummaryModal" runat="server" Width="500px" Height="500px" style="display: none; background-color:Black; color:#CCC;">
<asp:Button ID="btnExitRs" runat="server" Text="Hide Modal (Debug Purposes Only)" onclick="btnExitAct_Click" />
<asp:Label ID="lblReservationSummary" runat="server" Text="Label"></asp:Label>
</asp:Panel>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="HiddenField1" PopupControlID="reservationSummaryModal" BackgroundCssClass="modalBg" CancelControlID="btnExitRs">
</asp:ModalPopupExtender>
<asp:HiddenField ID="HiddenField1" runat="server" />
And here is my codebehind:
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ViewReservationDetails")
{
//GridViewRow gvr = gvReservationSummaries.Rows[Convert.ToInt32(e.CommandArgument)];
gvReservationSummaries.SelectedIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvReservationSummaries.Rows[gvReservationSummaries.SelectedIndex];
lblReservationSummary.Text = "The id is: " + gvr.Cells[0].Text.ToString();
ModalPopupExtender1.Show();
}
else if (e.CommandName == "ViewReceiptDetails")
{
gvReservationSummaries.SelectedIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvReservationSummaries.Rows[gvReservationSummaries.SelectedIndex];
lblReservationSummary.Text = "The id is: " + gvr.Cells[0].Text.ToString();
ModalPopupExtender1.Show();
}
else
{
}
}

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

Pass row index to modal popup window from buttonField in GridView

I have a GridView (see below) which uses ButtonField buttons to launch modal popup windows.
Here is the GridView
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_ButtonClick" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" CssClass="mGrid" AllowPaging="True" PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" OnRowEditing="GridView1_RowEditing" AutoGenerateColumns="False">
<AlternatingRowStyle BackColor="#F7F7F7" CssClass="alt" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<Columns>
<asp:BoundField HeaderText="BeaconID" ShowHeader="True" Visible="True" DataField="beaconObjectid" />
<asp:BoundField DataField="aliasName" HeaderText="My Beacon Name" />
<asp:ButtonField ButtonType="Button" CommandName="AssignName" Text="Assign Name"/>
<asp:BoundField HeaderText="Action Type" DataField="actionType" />
<asp:BoundField DataField="actionContent" HeaderText="Action Content" />
<asp:ButtonField ButtonType="Button" CommandName="AssignAction" Text="Assign/Change Action"/>
</Columns>
<PagerStyle CssClass="pgr" />
</asp:GridView>
This works fine to open the modal window like this one, using the C# code shown further down:
<asp:Button ID="showModal3" runat="server" Text="Show Modal" CssClass="hiddenButton"/>
<asp:Panel ID="Panel3" runat="server" CssClass="modalPopup">
<div class="header">
Set Alias Name
</div>
<div class="body">
Set a new name for your beacon
<br />
<br />
<div style="float: none;">
<asp:TextBox ID="AliasNameTextBox" runat="server" Height="21px" Width="300px"></asp:TextBox>
</div>
</div><br/>
<div class="footer" align="right">
<asp:Button ID="setAliasOK" runat="server" Text="OK" CssClass="yes" OnClick="setAliasOK_Click" CausesValidation="False" />
<asp:Button ID="setAliasCancel" runat="server" Text="Cancel" CssClass="no" />
</div></asp:Panel>
<ajaxToolkit:ModalPopupExtender ID="SetAliasNameModalPopupExtender" runat="server" CancelControlID="setAliasCancel" DropShadow="True" PopupControlID="Panel3" TargetControlID="showModal3" BackgroundCssClass="modalBackground"></ajaxToolkit:ModalPopupExtender>
In my C# code, i'm getting the index of the buttons like this so i know which row was clicked, which all works well:
protected void GridView1_ButtonClick(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = GridView1.Rows[Convert.ToInt32(e.CommandArgument)]; // this gets the row
string id = row.Cells[0].Text;
string name = row.Cells[1].Text;
string actionText = row.Cells[3].Text;
if (e.CommandName == "AssignName")
{
SetAliasNameModalPopupExtender.Show();
AliasNameTextBox.Text = name;
}
if (e.CommandName == "AssignAction")
{
ChooseActionModalPopupExtender.Show();
}
Label1.Text = name;
Label2.Text = actionText;
Label3.Text = id;
currentlySelectedRow = Convert.ToInt32(e.CommandArgument);
beaconIDnumber = id;
}
The problem is when i click the 'OK' button from my modal popup window. I need to have access to the row index from the gridview buttonfield that called it. My OK button click event looks like this:
protected void setAliasOK_Click(object sender, EventArgs e)
{
var newName = AliasNameTextBox.Text;
ParseChangeAliasName(beaconIDnumber, newName);
SetAliasNameModalPopupExtender.Hide();
}
So ultimately what i'm asking, is how do i pass the gridview row to the modal window so i can use data from the respective row cell - in this case the beacon ID (DataField="beaconObjectid" in the gridview).
I've even tried setting global variables in the GridView1_ButtonClick method, and then referencing them in the setAliasOK_Click method, but they get wiped as soon as the modal window opens.
Ideally i want to do this without using Javascript if possible.
in the same way you get
GridViewRow row = GridView1.Rows[Convert.ToInt32(e.CommandArgument)];
you can set your Button attributes:
setAliasOK.CommandName = "AliasOK" ;
setAliasOK.CommandArgument = e.CommandArgument ;
But you need to process your button's RowCommand event rather than the Click event to get to the Button's Command parameters

How to get Button1 Id on button2 click on server side asp.net c#

here is my aspx view
<asp:GridView ID="gvdatasubcategory" runat="server" AllowPaging="false" AllowSorting="false"
CssClass="gvdatarow" ShowHeader="false" AutoGenerateColumns="False" OnRowCommand="gvdatasubcategory_RowCommand">
<Columns>
<asp:TemplateField ItemStyle-Font-Names="Estrangelo Edessa" HeaderStyle-Font-Names="Estrangelo Edessa">
<ItemTemplate>
<div class="subcategory_type">
<div id="abd" runat="server">
<asp:LinkButton ID="button1" runat="server" CssClass="subcategory_name"
Width="80px" Height="26px" Text='<%#DataBinder.Eval(Container.DataItem, "SubCategory")%>'
CommandName="Test"></asp:LinkButton>
</div>
</div>
</ItemTemplate>
<HeaderStyle Font-Names="Estrangelo Edessa" Width="5px" />
<ItemStyle Font-Names="Estrangelo Edessa" Width="5px" Wrap="false" HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="button2 " runat="server" CssClass="category_name" Text="getid"
OnClick="button2 _Click" />
these buttons are in gridview and i need to get the first button id on second button click in code behind
Thank you in advance
Raveendra
If you are looking for Linkbutton object, thenyou can use FindControl method as:
LinkButton button1 = (LinkButton)gvdatasubcategory.Rows[0].Cells[0].FindControl("button1");
string buttonid = button1.ClientID; //gives client side id of the Linkbutton
But keep in mind that grid should contain th rows, otherwise you will get null. If you need all Linkbutton instances, then you can loop through the datarows to get each linkbutton ids.
You can try this code below:
protected void button2_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in gvdatasubcategory.Rows)
{
LinkButton btn = (LinkButton)row.FindControl("button1");
string strClientID = string.Empty;
strClientID = btn.ClientID;
}
}

Categories