How to get values from Controls which are in GridView? - asp.net

I am new to asp.net website developer.
In my website I use GridView Control.In the GridView row i place some controls like
TextBox,DropDownList.
I can display the values in GridView.
But my requirement is ,Get the values from TextBox and DropdownList Which are existed in GridView.
Please help me to go forward..
thank you,
bye..

You need to access them by row. This code project article explains it in detail.
TextBox tb = (TextBox)gridview1.Rows[0].FindControl("idOfTextBox");
It above statement will find control in the first row of grid which has id idOfTextBox and type is textbox.

You can directly get any value of any control by casting directly, without using an extra textbox or dropdown variable.
Example:
string val = ((TextBox)gridview1.Rows[0].FindControl("TextBox_ID")).Text;
Hope it helps :)

Subscribe the RowDataBound event(this will be fired on each row available in gridview) of gridview and access like stated below,
protected void grdBillingdata_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//these controls are available inside gridview
HiddenField hdnNagetiveAmt = (HiddenField)e.Row.FindControl("hdnNagetiveAmt");
DropDownList ddlFeeType = (DropDownList)e.Row.FindControl("ddlFeeType");
TextBox txtFeeDesc = (TextBox)e.Row.FindControl("txtFeeDesc");
Button btnUpdate = (Button)e.Row.FindControl("btnUpdate");
}
}

not only text box we can get values from all the controls that used inside gridview that placed by using itemTemplate or simply a Bound field .
you need to loop for each row to get the values
foreach (GridViewRow row in grd_popup_details.Rows)
{
//get control values
}
Refference link

Related

Click on Edit button in GridView puts wrong row in edit mode

I have gridview putting data from one table from database using stored procedure.
On click of Edit Button, post back is happen which refreshing the data on gridview and wrong row is shown in edir mode.
I have found the reason is that on click on EDIT link javascript:__doPostBack('GridView','Edit$0') is displayed at the status bar, which is a problem here. Edit$0 means the absolute value of the row and when postback get the data from data base wrong row is shown in edit mode...
I think the solution will be put the edit mode based on not row number but some unique value of the selected row for edit.
Please help if any one has answer to it.
If you're using a gridview I suggest using the native OnRowEditing="GridViewEditEventHandler"
and then in the code behind
protected void TaskGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
TaskGridView.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindData();
}
see http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowediting(v=vs.110).aspx
However, if for some reason you are creating an OnClick function when you press the edit button and then changing the Itemtemplate to show/hide values I would suggest doing
GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
from there you can do the .findcontrol to find the specific item you want ex:
TextBox txtbox = (TextBox)TaskGridView.Rows[RowIndex].FindControl("textBoxID");
Hope this helps

ASP.NET Boundfield changes when I update another gridview

I have a boundfield in a gridview that programatically receives a hyperlink for the content in it. It gets a new dataset after a drop down list index change. One of the columns of the dataset will apply links to fields with data and skip those without, you can see my logic for applying links below:
if (e.Row.DataItem != null && int.TryParse(e.Row.Cells[4].Text, out incidents))
{
HyperLink incidentsLink = new HyperLink();
incidentsLink.ForeColor = System.Drawing.Color.Blue;
incidentsLink.NavigateUrl = "~/somesite.aspx?no=" + stnNum + "&dt=" + date;
incidentsLink.Text = e.Row.Cells[4].Text;
e.Row.Cells[4].Controls.Add(incidentsLink);
}
This is applied OnRowDataBound for the gridview. Then I have another gridview that is wired to another drop down list. When either drop down list changes index it grabs a new dataset for the related gridview and fires a ajax update using an update panel.
What happens is when the second gridview updates it erases the links in the first gridview. It doesn't erase the text, that stays, but the text is no longer anchored to a link. All links made this way and put into gridviews lose their link properties, however fields created using asp:HyperLinkField are left unchanged. The problem is that stnNum and date are not a part of the dataset that is returned for the first gridview, so I have to add them as a link after the gridview is already built.
The only solution I can think of is to refire the function that adds links to the gridview each time the second gridview updates. Any other solutions would be helpful, or an explanation as to why my link is being erased would be great.
Try binding the GridView/DropDowns only if there is not any POSTBACK. I believe POST Back event is letting your gridview & Controls to loose their data somehow.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Bind your Grids & Dropdowns here on page load
}
}

dynamic columns disappears after postback

I have a GridView with some BoundFields and two TemplateFields. In these two TemplateFields, I dynamically create UserControls containing a DropDownList and a TextBox, which users can modify.
When I try to get the values of the controls after a PostBack, the values in BoundFields are still there but my dynamic controls disappears. I can create them again but it won't get the user's values... How can I get these values before they're lost?
Here's some of my code:
In the RowDataBound event:
Select Case type
Case "BooleanBis"
e.Row.Cells(2).Controls.Clear()
Dim list1 As BooleanBisList = New BooleanBisList(avant, False)
e.Row.Cells(2).Controls.Add(list1)
e.Row.Cells(4).Controls.Clear()
Dim list2 As BooleanBisList = New BooleanBisList(apres, True)
e.Row.Cells(4).Controls.Add(list2)
Case "Boolean"
e.Row.Cells(2).Controls.Clear()
Dim list3 As BooleanList = New BooleanList(avant, False)
e.Row.Cells(2).Controls.Add(list3)
e.Row.Cells(4).Controls.Clear()
Dim list4 As BooleanList = New BooleanList(apres, True)
e.Row.Cells(4).Controls.Add(list4)
End Select
In my button click event, I try to get the user control :
Case "String"
temp.ChampValeurApres = DirectCast(Tableau1.Rows(i).Cells(selectedColumn).Controls(1), TextBox).Text
but i get the error that it doesn't exist.
You should create dynamic controls in RowCreated instead of RowDataBound because this event gets fired on every postback whereas RowDataBound only will fire when the GridView gets databound to it's DataSource.
Dynamically created controls must be recreated on every postback with the same ID as before, then they retain their values in the ViewState and events will fire correctly(f.e. a DropDownList's SelectedIndexChanged event).
So you should create them in RowCreated and "fill" them in RowDataBound(f.e. the DropDownList datasource/Items or a TextBox-Text).
I had been using:
EnableViewState="false"
in the GridView attributes. Removing it solved my problem!
I just did
protected void Page_Load(object sender, EventArgs e)
{
if (!(Page.IsPostBack))
{
// Put the selected items which u want to keep on postback
}
else
{
//regenerate auto created controls
}
}
and it worked as well

asp:GridView doesn't contain control added in OnRowDataBound

I have problem, I can't get control which I added in DataGrid. I am adding it in OnRowDataBound event like:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == (DataControlRowState.Alternate | DataControlRowState.Edit))
{
//int cindex = 0;
//for (cindex = 0; cindex < e.Row.Controls.Count; cindex++)
foreach (Control ctl in e.Row.Controls)
{
DataControlFieldCell dcctl = (DataControlFieldCell)ctl;
TableCell tcell = (TableCell)dcctl;
Label lblComment = new Label();
TextBox txtComment = new TextBox();
lblComment.Text = "<br>Comment: ";
dcctl.Controls.Add(lblComment);
dcctl.Controls.Add(txtComment);
//tcell.Controls.Add(lblComment);
//tcell.Controls.Add(txtComment);
//e.Row.Cells[cindex].Controls.Add(lblComment);
//e.Row.Cells[cindex].Controls.Add(txtComment);
What is happening here: there is already exist one TextBox in TableCell by default and I want to add another one TextBox and Label. After the bounding I can see 2 textboxes, I can input data into the both, but when I click Update button, then raises OnRowUpdating event where I can't get my TextBox!
protected void RowUpdating(object sender, GridViewUpdateEventArgs e)
{
grdView.EditIndex = -1;
int counter = 0;
for (counter = 0; counter < grdView.Rows[e.RowIndex].Cells.Count; counter++)
{
foreach (Control ctl in grdView.Rows[e.RowIndex].Cells[counter].Controls)
{
And here I will be getting only default one TextBox (with its value). But my TextBox is disappeared! :(
What could you suggest me here to do?
P.S. I can't use predifined columns, like asp:TemplateField in aspx file, because my table has different amount of rows every time. It is dynamic
The issue is that after you dynamically add a control to a page (or any of the page's child controls such as your datagrid) then you must recreate the controls on the server side on postback. If you don't recreate the controls on the server side, then when the runtime processes the postback it will have no idea where to put the contents of the form post.
So essentially when the page is processing the postback, it sees an HTML field called "gridView1_txtComment" (the actual HTML id is probably something else, I know). But the server side code model only has an instance of gridView1, there isn't an instance of a TextBox named txtComment unless you run the RowDataBound method again to create that control.
I think it has to do with ViewState. Make a templated column out of it, then add the second textbox to the template.
I did it!
Refused of dynamically adding controls in OnRowDataBound, and created dynamical TempalteField columns, which were containing needed to me 2 TextBoxes and Label. (With help of http://www.codeproject.com/KB/aspnet/create_template_columns.aspx)
But after my problem returned back.. On OnRowUpdating event still was not having my added TextBoxes. Finally I've found here notice http://forums.asp.net/p/1537632/3738331.aspx, that it is needed to implement TempalteField-s adding on Page_Load, that helped me to solve the problem!

Asp.Net Gridview Buttonfield get Row Data

I have a Gridview which is binded to a datatable that I created. The data in the table is ever changing.
I added a buttonfield to the Gridview. When clicked I want to send a specific columns value in that row through a link or sent through a function.
How do you go about doing this?
I found out how to do it. You set the commandName property to whatever you want to call it inside the properties.
Then if you double click on the button after creating it in design view, it should pop up a function in the code behind page. You can then access the row by doing the following.
protected void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowNum = int.Parse(e.CommandArgument.ToString());
}
from there you can use the row number to access specific column data.
Here's a decent example from MSDN: http://msdn.microsoft.com/en-us/library/bb907626.aspx

Resources