How to get the modified textbox value in c#? - c#

I used a textbox in gridview to bind a value from db during pageload..
The problem is when i change the textbox value i could not get the modified value in c#, instead it gives the original value which had been there before i modified..
I am using nested GridViews...
kindly help me..
<asp:TemplateField HeaderText="Singles" >
<ItemTemplate>
<asp:HiddenField ID="hidqua" runat="server" Value='<%#bind("QualityName") %>' />
<asp:HiddenField ID="hidfau" runat="server" Value='<%#bind("FaultName") %>' />
<asp:TextBox ID="asptxtsingleg" runat="server" Text='<%# bind("singles") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
and below is my c# Coding
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "update")
{
foreach (GridViewRow row in grdInspection.Rows)
{
HiddenField hv = (HiddenField)row.FindControl("hidval");
GridView txtsi = (GridView)row.FindControl("grdInsiewChid");
foreach (GridViewRow row1 in txtsi.Rows)
{
HiddenField htn = (HiddenField)row1.FindControl("hdnPLength");
GridView nesgrid = (GridView)row1.FindControl("GridView1");
foreach (GridViewRow row2 in nesgrid.Rows)
{
HiddenField qn = (HiddenField)row2.FindControl("hidqua");
TextBox t = (TextBox)row2.FindControl("asptxtsingleg");
}
}
}
}
}

Assuming you are using button to fire the RowCommand event.
<asp:TemplateField HeaderText="Singles">
<ItemTemplate>
<asp:TextBox ID="asptxtsingleg" runat="server" Text='<%# Eval("singles") %>' Width="120px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Update" CommandName="updateData" CommandArgument='<%# Eval("Your_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
Code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "updateData")
{
//int i = Convert.ToInt32(e.CommandArgument);
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
TextBox tb = (TextBox)row.FindControl("asptxtsingleg");
}
}

You can use below code to get the text box value in RowUpdating event
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox t= (TextBox)row.FindControl("asptxtsingleg");

Related

Hidden template field value not avaialble on server Side

I am working on Asp.net and stuck in middle.
I have a gridview with template field.Gridview have 3 columns and I want to pass value of two columns to server Side.
Scenario-On Clicking lnkRemove(LinkButton),the GUID should be passed(which is getting passed in Command arguement) and also the value of SEQ_NBR column(passing this value is problem for me)
I am trying with Hidden field but how to get hiiden field value in Server Side code(i.e Deletedata).
Code
<asp:GridView>
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "SEQ_NBR">
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"
Value='<%# Eval("SEQ_NBR") %>' />
<asp:Label ID="SEQ_NBR" runat="server"
Text='<%# Eval("SEQ_NBR")%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="SEQ_NBR" runat="server" ReadOnly="true" Text="Auto generated"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument = '<%# Eval("GUID")%>'
OnClientClick = "return confirm('Do you want to delete?')"
Text = "Delete" OnClick = "Deletedata"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And my server side code is:
protected void Deletedata(object sender, EventArgs e)
{
//I want Hiddden field value here;I tried below code but not working.Any suggestion .
chkSelect = GridView.Controls[0].Controls[0].FindControl("HiddenField1");
}
Don't use
GridView.Controls[0].Controls[0].FindControl("HiddenField1");
but on the GridViewRow since that is the NamingContainer:
GridView.Rows[0].FindControl("HiddenField1");
But in this case you want to find the hiddenfield from the LinkButton's click-event. Therefore use following approach. The LinkButton's NamingContainer is the GridViewRow:
protected void Deletedata(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton) sender;
GridViewRow row = (GridViewRow) lnkRemove.NamingContainer;
HiddenField hf = (HiddenField) row.FindControl("HiddenField1");
string seqNbr = hf.Value; // voilĂ 
}
Try this one
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
GridView.SelectedIndex = row.RowIndex;
var HiddenField= GridView.Rows[gridMain.SelectedIndex].FindControl("HiddenField1") as HtmlInputHidden;
if (HiddenField!= null)
{
sting strValue = HiddenField.Value;
}

How to get row data by clicking a button in a row in an ASP.NET gridview

I have a GridView in a ASP.NET web application, in which I have added two buttons in each row:
<ItemTemplate>
<asp:Button ID="btnEdit" Text="Edit" runat="server" />
<asp:Button ID="btnDelete" Text="Delete" runat="server"/>
</ItemTemplate>
Now how I can get the row data from gridview simply by clicking an edit button in a row?
You can also use button click event like this:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
</asp:TemplateField>
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
OR
You can do like this to get data:
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = CustomersGridView.Rows[index];
}
}
and Button in gridview should have command like this and handle rowcommand event:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
onrowcommand="CustomersGridView_RowCommand"
runat="server">
<columns>
<asp:buttonfield buttontype="Button"
commandname="Select"
headertext="Select Customer"
text="Select"/>
</columns>
</asp:gridview>
Check full example on MSDN
Place the commandName in .aspx page
<asp:Button ID="btnDelete" Text="Delete" runat="server" CssClass="CoolButtons" CommandName="DeleteData"/>
Subscribe the rowCommand event for the grid and you can try like this,
protected void grdBillingdata_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteData")
{
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
HiddenField hdnDataId = (HiddenField)row.FindControl("hdnDataId");
}
}
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
and your method
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
Is there any specific reason you would want your buttons in an item template.You can alternatively do it the following way , there by giving you the full power of the grid row editing event.You are also given a bonus of wiring easily the cancel and delete functionality.
Mark up
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="EditImageButton" runat="server" CommandName="Edit"
ImageUrl="~/images/Edit.png" Style="height: 16px" ToolTip="Edit"
CausesValidation="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update"
Text="Update" Visible="true" ImageUrl="~/images/saveHS.png"
/>
<asp:LinkButton ID="btnCancel" runat="server" CommandName="Cancel"
ImageUrl="~/images/Edit_UndoHS.png" />
<asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete"
ImageUrl="~/images/delete.png" />
</EditItemTemplate>
<ControlStyle BackColor="Transparent" BorderStyle="None" />
<FooterStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
Code behind
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
TextBox txtledName = (TextBox) GridView1.Rows[e.NewEditIndex].FindControl("txtAccountName");
//then do something with the retrieved textbox's text.
}
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="LnKB" Text='edit' OnClick="LnKB_Click" >
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
protected void LnKB_Click(object sender, System.EventArgs e)
{
LinkButton lb = sender as LinkButton;
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
int x = clickedRow.RowIndex;
int id = Convert.ToInt32(yourgridviewname.Rows[x].Cells[0].Text);
lbl.Text = yourgridviewname.Rows[x].Cells[2].Text;
}
<asp:Button ID="btnEdit" Text="Edit" runat="server" OnClick="btnEdit_Click" CssClass="CoolButtons"/>
protected void btnEdit_Click(object sender, EventArgs e)
{
Button btnEdit = (Button)sender;
GridViewRow Grow = (GridViewRow)btnEdit.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("txtAccountName");
HyperLink HplnkDr = (HyperLink)Grow.FindControl("HplnkDr");
TextBox txtnarration = (TextBox)Grow.FindControl("txtnarration");
//Get the gridview Row Details
}
And Same As for Delete button
protected void btnS10_click(object sender, EventArgs e)
{
foreach (GridViewRow row in Grd.Rows)
{
CheckBox chk_Single = (CheckBox)row.FindControl("ChkSendOne");
if (row.RowType == DataControlRowType.DataRow)
{
string id = (row.Cells[0].FindControl("lblSNo") as Label).Text;
if (Convert.ToInt32(id) <= 10)
{
chk_Single.Checked = true;
if (chk_Single.Checked == true)
{
lblSelectedRecord.InnerText = (Convert.ToInt32(lblSelectedRecord.InnerText) + 1).ToString();
}
}
}
}
}

Find header value for a cell in a grid

I have gridview, I want to do a foreach on it's rows and get the value from column's header where there's a Label for one cell from this row.
foreach (GridViewRow mainRow in grid1.Rows)
{
var header = mainRow.Cells[2].Parent.FindControl("LabelID");//is null
}
How do I find it ?
If you want the value in RowDataBound event then you can check RowType like this
if(e.Row.RowType == DataControlRowType.Header)
{
Label header = (Label)e.Row.FindControl("LabelID");
}
I would access the headerRow and enumerate through the according cells (on buttonClick or on RowDataBound ...)
default.aspx
<asp:GridView AutoGenerateColumns="false" ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="headerLabel1" runat="server" Text="Headercolumn1"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="itemLabel1" runat="server" Text='<%# Eval("name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnGetHeader" runat="server" Text="GetHeader" OnClick="btnGetHeader_Click" />
default.aspx.cs
protected void btnGetHeader_Click(object sender, EventArgs e)
{
foreach (TableCell headerCell in GridView1.HeaderRow.Cells)
{
// or access Controls with index
// headerCell.Controls[INDEX]
Label lblHeader = headerCell.FindControl("headerLabel1") as Label;
if (lblHeader != null)
Debug.WriteLine("lblHeader: " + lblHeader.Text);
}
}

How to reference a linkbutton thats inside a asp:grid when its clicked

I have a ASP:grid which has a link button, i need to some how reference that on the code behind when its clicked but im struggling on the syntax
Heres my ASP:Grid i need to execute code in the code behind when that link button 'Re-Take' is pressed and also be able to know what row it was clicked on as i will need to reference the users emails and name and then send an email with the relevant information....
<asp:GridView ID="GrdViewUsers" runat="server" AutoGenerateColumns="false" GridLines="None"
EnableViewState="false" class="tablesorter">
<AlternatingRowStyle></AlternatingRowStyle>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Re-Take" runat="server" ID="Edit" CommandName="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Full Name">
<ItemTemplate>
<asp:HyperLink ID="HyperFullName" CssClass="gvItem" runat="server" NavigateUrl='<%#Eval("UserID","/ExamPaper.aspx?uid={0}") %>'
Text='<%# DataBinder.Eval(Container,"DataItem.FullName") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lblSurname" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam Taken">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ExamTaken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Taken">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.DateTaken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam Total">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ExamTotal") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If someone can help me with a snippet i would highly appreciate it
You could approach this slightly different. You see, when a control is placed inside a gridview, any event raised from that control raises also the RowCommand on the GridView.
To get what you want you could then add both CommandName and CommandArgument to your LinkButton and then catch it in the GridView's RowCommand.
<asp:LinkButton id="LinkButton1" runat="server" commandName="LinkButtonClicked" commandArgument='Eval("myObjectID")' />
where myObjectID is the name of the ID column of your object you bind the grid to.
Then
void GridView1_RowCommand( object sender, GridViewCommandEventArgs e )
{
if ( e.CommandName == "LinkButtonClicked" )
{
string id = e.CommandArgument; // this is the ID of the clicked item
}
}
see: ASP.net GridView: get LinkItem's row
FindControl should work in this case.
protected void GrdViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink myHyperLink = e.Row.FindControl("Edit") as HyperLink;
}
}
First: You have repeating ID's in your TemplateFields like lblUsername what is not allowed since it's the same NamingContainer.
You can pass the RowIndex as CommandArgument to RowCommand:
on aspx:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton
Text="Re-Take"
runat="server"
ID="Edit"
CommandName="Edit"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Handle the GridView's RowCommand:
void GrdViewUsers_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Edit")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GrdViewUsers.Rows[index];
// now you can get all of your controls like:
Label lblSurname = (Label)row.FindControl("lblSurname");
String email = lblSurname.Text // you noticed that DataItem.Email is bound to lblSurname?
}
}
Suppose the grid has linkbutton on which we want to get row index
<asp:LinkButton ID="lnkbtnAdd " runat="server" CommandName="cmdAdd" ImageUrl="~/Images/add.gif" ></asp:LinkButton>
In code behind, In OnRowCreated event we attach row number of grid to each button of row to get it back when it is clicked in RowCommand event
protected void gvListing_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.LinkButton lnkbtnAdd = new System.Web.UI.WebControls.LinkButton();
lnkbtnAdd = (System.Web.UI.WebControls.LinkButton)e.Row.FindControl("lnkbtnAdd");
if (lnkbtnAdd != null)
lnkbtnAdd .CommandArgument = e.Row.RowIndex.ToString();
}
}
In RowCommand event we will get back the current row index and set the selected index of the grid
protected void gvListing_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "cmdAdd")
{
int RowIndex = int.Parse(e.CommandArgument.ToString());// Current row
}
}

Find out a CHECKBOX in a DATAGRID in ASP.NET

I have a GRIDVIEW and with several CHECKBOXS.
When i selected a CHECKBOX I need run some code.
To detect it, I use an EVENT HANDLER for the CHECKBOX included in a GRIDVIEW.
I cannot access the CHECKBOX with my wrong code.
Do you have any idea what I am doing wrong? Thanks for your help. Bye
ASPX
<asp:Label ID="uxMessageDisplayer" runat="server" Visible="False" EnableViewState="False"></asp:Label>
<asp:GridView ID="uxUserListDisplayer" runat="server" AutoGenerateColumns="False"
OnRowDataBound="uxUserListDisplayer_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:CheckBox ID="uxActiveCheckBoxSelector" runat="server" AutoPostBack="true" OnCheckedChanged="uxRoleCheckBoxSelector_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Users">
<ItemTemplate>
<asp:Label runat="server" ID="uxUserNameLabelDisplayer" Text='<%# Container.DataItem %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkEditButton" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkDeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CODE BEHIND
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Reference the CheckBox that raised this event
//CheckBox uxActiveCheckBoxSelector = sender as CheckBox;
CheckBox activeCheckBox = (CheckBox)FindControl("uxActiveCheckBoxSelector");
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
uxMessageDisplayer.Enabled = false;
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
uxMessageDisplayer.Enabled = false;
}
}
If I am not mistaken by your question, you are trying to set the text of the label on the same row with the checkbox based on its checked status.
Below is the code snippet I tried on my pc, hope it helps.
.aspx:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;
//create dummy data
List<string> rows = new List<string>();
Enumerable.Range(1, 5).ToList().ForEach(x => rows.Add(x.ToString()));
//bind dummy data to gridview
GridView1.DataSource = rows;
GridView1.DataBind();
}
protected void CheckBox1_CheckChanged(object sender, EventArgs e)
{
//cast sender to checkbox
CheckBox CheckBox1 = (CheckBox)sender;
//retrieve the row where checkbox is contained
GridViewRow row = (GridViewRow)CheckBox1.NamingContainer;
//find the label in the same row
Label Label1 = (Label)row.FindControl("Label1");
//logics
if (CheckBox1 != null) //make sure checkbox1 is found
{
if (CheckBox1.Checked)
{
if (Label1 != null) //make sure label1 is found
{
Label1.Text = "Checked";
}
}
else
{
if (Label1 != null)
{
Label1.Text = "Unchecked";
}
}
}
}
I'm assuming the event handler is actually registered to the checkbox.
CheckBox activeCheckBox = (CheckBox)sender;
what is "uxActiveCheckBoxSelector" and why are you ignoring sender?
Code corrected as suggest!
Usefull resource for beginners
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Cast sender to CheckBox
CheckBox activeCheckBox = (CheckBox)sender;
// Retrieve the row where CheckBox is contained (NamingContainer used to retrive parent control
GridViewRow row = (GridViewRow)activeCheckBox.NamingContainer;
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
}
}

Categories

Resources