PostbackUrl of dynamic GridViews not what I think they should be - c#

I have a couple GridViews that are dynamically created and placed into a PlaceHolder. When I mouse over the Select button, it shows __doPostBack('ctl00$bodyPlaceHolder$ctl0X','Select$Y'), where X = what I think is the GridView/Control index for the page and Y = row number of that GridView.
Since it is dynamically creating the GridViews, it makes sense that names them ctl0X, but on the PostBack how do I use this information?
I wouldn't even have this problem if adding the SelectedIndexChanged EventHandler worked, but it never gets called.
I found one other question like this, but the answer involved adding a GridView within my GridViews, which would also have to be dynamic, which brings me back to the original problem.
Edit
Okay, so I set gridViewDynamic.ID = "blahblah" + r.LastName, thus giving each GridView a unique name, so on mouseover in the page I get __doPostBack('ctl00$bodyPlaceHolder$blahblahSmith',Select$Y, I still can't access the items on PostBack because they no longer exist. So, I added the same GridView creation code to an if(IsPostBack), then called GridView gView = (GridView)this.Page.FindControl(blahblahSmith). Great, gView isn't null. But all the data in the rows are. Calling gView.Rows[0] returns null.

Use Page.FindControl("TheNameYouGaveTheDynamicGridView")
GridView grid = Page.FindControl("TheNameYouGaveTheDynamicGridView") as GridView;
If you are using MasterPages, you need to take a different approach to find the control on the page, but it is the same premise.

Related

How to save the drop down list selected index in asp.net?

i want that after clicking a button saves the index i have selected in order to storage that number to my database. My drop-down-list is in a comment below.
The drop-down-list is filled by using a query. And so far what it does, is that after clicking the button it storages the first index (which is 0), even when i want to save another index.
I have done some research, and so far i cannot solve it, hope someone can help me out.
Code for Dropdown list:-
<asp:DropDownList ID="ddlCategory" runat="server" Height="25px" Width="428px" Font-Size="Large"> </asp:DropDownList>
here's how i fill the drop-down-list
ClsUtil clsutil = new ClsUtil();
DataSet ds = clsutilerias.FillDDL(Category);
ddlCategory.DataTextField = ds.Tables[0].Columns["Name"].ToString();
ddlCategory.DataValueField = ds.Tables[0].Columns["Category_ID"].ToString();
ddlCategory.DataSource = ds.Tables[0];
ddlCategory.DataBind();
The DropDownList has properties. You need to set SelectedIndex, SelectedItem or SelectedValue properly (and in the correct event in relation to when you do the binding etcetera).
Edit: Maybe you updated your question, or maybe I misunderstood, but either way it seems now that you don't want to set the SelectedIndexperhaps as much as get the SelectedIndex. Even so, if you read the documentation and look at the examples provided in the links, you should have enough information to know what to do.
Basically, one of the <option> elements in the <select> on the client (the HTML code) will be selected when the data is posted back to the server. If your <asp:DropDownList> is AutoPostBack="True" you can go for a callback in the OnSelectedIndexChanged event, but there are other ways too, with or without auto-post-back. (You don't really need the view state, or even the <asp:DropDownList> at all, but can trigger a POST by submitting the form data in any way that suits your needs or preferences, and then read any values your interested in server-side.)
It seems that you found your solution in checking IsPostback in the Page, and not re-populate the list if the value is true. That's good. If you don't need to data-bind every time you render the page (even after a POST), that's a viable and common solution.
Another option, of course, would be to read the posted data in any event that happens before you do the data-binding. You may also want to handle the value of SelectedIndex to re-select the correct option in your drop-down after having populating it again, if you don't like having ASP.NET doing it for you.
When you are clicking the button, the entire page is refreshing that why you got the first index all the time
The best solution is :
if(IsPostBack == false)
{
//Save your data code here
}
You have other tricky solution which is :
put the dropboxmenu inside an update panel control
While binding datasource to combo, mention DataMember and DataValue property for combo box so that selecting elements from combo you get selectedValue as DataValue.
Well i have solved my problem, my problem was that when i clicked the button, the pageLoad method executed again, and there was where i had the code to fill my drop-down-list. so i just added:
if(!IsPostBack)
{
//here goes the code to fill the Drop down list
}

Refreshing a particular cell of a grid without loading entire grid view

Is there any way to refreshing a cell of a grid view without refreshing the entire grid view in c# asp.net
you could possibly use a templatefield, put an UpdatePanel in it and refresh that single cell that way. You would just need someway to initiate the refresh.
You may have to use a nested UpdatePanel within the cell.
If you don't want to put an UpdatePanel in every cell in your GridView, you can refresh a cell on a regular, full postback. The contents of the grid will be roundtripped, but your data source won't necessarily be queried in full.
First, make sure your grid doesn't rebind on every postback, e.g. wrap your gv.DataSource = x; gv.DataBind(); inside an if (!this.IsPostBack).
Then you should be able to do something along the lines of
((Label)gv.Rows[x].Cells[y].FindControl('myLabel')).Text =
GetDataItemNumber(x).FieldForColumnY.ToString();
Bear in mind that gv.Rows[x] may not correspond to the xth item in your data source, as Rows includes header rows etc. You might need to iterate through Rows checking e.g. IDs to find the correct row.
Disclaimer: I've never actually done this before, but it should be possible...

GridView RowCount late update updatepanel

I have a gridview in an updatepanel where also my dropdownlist is. From the Trigger of the dropdownlist I am refreshing my gridview with the slected value. All that is working fine. The problem is that I am also displaying the gridview row count on the page which is also inside the updatepanel. The update seems to be happening to it, one selection too late.
protected void Drop_Change(object sender, EventArgs e)
{
String Value = AjaxDrop.SelectedValue;
GridView1.SelectParameters["Target"].DefaultValue=Value;
RowCount.InnerText = GridView1.Rows.Count.ToString();
}
I think its happening one selection behind because the parameter updates the gridview rowcount too late for the RowCount value to have it, what is a work around to get the actual value after parameter passed. Only way I can think of is using javascript and I wonder if that would even work. My desired solution would be to keep it all on server side though.
At the time you're calling this, the GridView hasn't done it's databinding, therefore the value is not valid. Move your RowCount.InnerText updating to somewhere that gets executed after the DataBinding event (e.g. Page_OnPreRender), or force the DataBinding to occur before you update the row count.
It's worth noting that GridView.Rows.Count isn't a reliable source of information if you are using GridView paging - as this will be the number of rows on one page, even if there are more rows returned by the query.

Read a dynamically created textbox in a Gridview

I am dynamically adding a textbox to certain rows (one column only) of a gridview. I add the controls with this insdie of a test condition (works fine):
TextBox txtASIN = new TextBox();
txtASIN.ID = "TxtASIN" + e.Row.RowIndex;
e.Row.Cells[4].Controls.Add(txtASIN);
int i = e.Row.Cells[4].Controls.Count; //TEST: This returns 1 correctly
I want the user to be able to enter values into one or more of these textboxes and then update the database with a single button click (not one click for each row). The problem I'm having is how to access those values on a button click event. I did a simple test this way to try to see the value in the second row but get null in temp1 (I am certain there is a value entered in that textbox):
protected void btnUpdate1_Click(object sender, EventArgs e)
{
TextBox temp = (TextBox)GridView2.Rows[1].FindControl("txt1");
string temp1 = temp.Text;
int i = GridView2.Row.Cells[4].Controls.Count; //TEST: This returns 0 incorrectly }
Once I can make this work, I can iterate through the rows and do what I need to do with the values. I don't know if the text entered in the textbox is actually readable without a postback but I'm otherwise stumped. Open to better suggestions on how to do this.
Thanks.
EDIT: Here is where I am now. I can see the textboxes in my column fine. I put a break in on a button that attempts to read them and this is what I'm seeing. If I check GridView2.Rows[0].Controls.Count, I get 8, which is the correect number of columns. If I check GridVeiw2.Rows[0].Cells[4].Controls.Count, I get 0, which is wrong because the textbox is there. I can get a Count of 1 right after I dynamically create it but not when I perform a subsequent button click.
Can anyone explain this? I feel if I can get past this holdup, I can get the rest done.
Thanks again.
You need to assign an ID to the TextBox controls and then access them by that ID in FindControl(). Also, make sure you're adding the controls in the Page's Init() method of the life-cycle. That way it gets added to ViewState.
TextBox txt1 = new TextBox();
txt1.ID = "txt1";
e.Row.Cells[4].Controls.Add(txt1);
EDIT: I just remembered another possible solution. Instead of programatically creating the TextBox controls in the code-behind just create a TemplateField in the GridView.
Add Textbox TemplateField Column To GridView Programmatically
I would try a different approach, putting the text box in the html markup of the page and then control the visible or readonly property of it on the ItemDataBound event. That way, the control will always be there and you don't have to worry about the lifecycle stuff.

How to hide the empty Column

Using C# & asp.net
if there is no data's in the table, gridview displaying one rows (it was empty)
I want to hide the gridview empty row.
How to do this.
Assuming that you can normally delete that one visible row just check that if a field that would normally have a value is empty and the row count is 1 then delete that row.
if(String.IsNullOrEmpty(mydatagrid.Rows[0][0].ToString()) && mydatagrid.Rows.Count==1) //Check a field that would normally have a value
{
mydatagrid.Rows.RemoveAt(0);
}
Let me know if this helps/works
If you are manually data binding than you can check at that time and hide or disable the control if there is no data. If you are data binding using the design view than you should subscribe to the DataBinding or the PreRender events on the control and check then.
you can check if the datatable doesn't have any rows
use:
mydatagrid.DataSource=null;
mydatagrid.DataBind();
As the other two comments you can either check in code and set MyDataGrid.Visible to true or false to hide the entire table, or you can not bind the datasource, or you can EmptyDataTemplate option to display whatever you want when there is no data for the GridView to display normally.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate.aspx
The normal behavior for GridView is to render NOTHING if there are no data rows. (Well, almost nothing; it insists on rendering a <div> wrapper, but that'll be empty.)
If you specify an EmptyDataTemplate, however, a one-celled wrapper table is generated to contain whatever is in your template. Even if your template is empty, you'll get that wrapper table (with its one cell, empty). Sounds like the answer to your question is don't specify an EmptyDataTemplate.

Categories