I have a grid. First the grid row is filled with row id (ie."tr" id) but when a button clicked (.Net Ajax) page gets refreshed. Then grid row id will disappear. How can this issue be resolved. I mean i need to retain row id when grid gets refreshed through Ajax call.
More clarity with call of ajax, grid row is losing the id. I need to retain that value. Is any method for that? Please help me.
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "javascript:ChangeRowColor(" + e.Row.ClientID + ")");
}
}
Above is the code, after refreshing with ajax method, its row id gets null. So, at runtime i'm getting js error like id is not defined.
Are you saying that e.Row.ClientID is null or empty after the postback? Instead of passing the ID of the row, just pass the row itself using this:
e.Row.Attributes.Add("onclick", "javascript:ChangeRowColor(this);");
By doing this, you no longer have to use document.getElementById either, since the element will be passed in as an argument:
EDIT: This is a quick & dirty solution, but you can use a global variable to keep track of the previously selected row.
var previousRow;
ChangeRowColor = function(row){
if (previousRow){
previousRow.style.background = 'white';
}
row.style.background = "red";
previousRow = row;
}
Related
I am getting value from textbox in gridview and trying to change the value with two different buttons. (increase and decrease buttons) First click is working than not working.
I was checking browser's console for getting information and i am getting this information: "XHR finished loading: POST" Do you have an idea why button click works only once?
Here is my code for increase:
public void btn_increase_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in gridview1.Rows)
{
Textbox quantity = (Textbox)row.FindControl("txt_quantity");
int input_quantity = Convert.ToInt32(quantity.Text);
if(input_quantitiy >= 0)
{
quantity.Text = Convert.ToString(input_quantity + 1);
}
}
}
UPDATED
If you have copied that code exactly from your program there are a few issues you could try fixing that might help:
input_quantity in the if() statement is spelt incorrectly.
Swap the = and > around in the if statement, currently isn't checking for greater than or equal too, but is a lambda expression.
Also if you know the ID of the TextBox, and only need to increase/decrease one TextBox, is there any reason to iterate through the GridView? You could achieve the same thing as follow:
TextBox quantity = txt_quantity;
int input_quantity = Convert.ToInt32(quantity.Text);
if (input_quantity >= 0)
{
quantity.Text = Convert.ToString(input_quantity + 1);
}
I found a solution and it's very simple. If your button click is not working and getting "XHR finished loading: POST" error on browser. Check your Page_Load and be sure bind gridview in if page is not postback like that:
if(!IsPostBack)
{
gridview.DataSource = dataset.Tables[0];
gridview.DataBind();
}
I want to add value into a Grid view via dropdownlist with a button.
I want the ddTN.SelectedItem.value in the Grid view to be unique. No duplication
How do I check every row for the ddTN.SelectedItem.value before adding a new ddTN.SelectedItem.value into the Grid view?
This are the codes that I have and it keep comparing the value with the first value in the gridview. Not the others.
I don't want to use a checkbox and such. All the example I found required using checkbox.
protected void Insert(object sender, EventArgs e)
{
int i = 0;
var p = 1;
DataControlFieldCell cell = GridView1.Rows[i].Cells[p] as DataControlFieldCell;
if (cell.Text != ddTN.SelectedItem.Value)
{
dt.Rows.Add(ddTN.SelectedValue, ddDuration.SelectedValue);
ViewState["Customers"] = dt;
this.BindGrid();
label.Text = "";
p++;
}
else
{
label.Text = "Exercise already inserted";
}
}
It looks like you were intending on looping over the items in the grid but you have forgotten the looping mechanism. In your code, it always only checks the first item because i is initialized to 0 and never changes.
Try using a looping mechanism like a for loop or a while loop. Or, if you know the items in the grid from the beginning, perhaps use a hash table for quickly checking if the selected item already exists.
Keep trying, you are almost there!
I have a GridView which loads some data on Load like this:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!Page.IsPostBack)
{
DataTable dataSource = LoadObjects();
gvObjects.DataSource = dataSource;
}
}
I've also added a SelectedIndexChanged event handler where I want to perform some functions whenever a row is selected. The problem is that unless I remove the IsPostBack check from the OnLoad method, when a row is selected the GridView.SelectedRow attribute is not the row I selected.
Ideally I don't want to load all my data from the database on each postback. Are there any best-practices to get the selected row during the SelectedIndexChanged event without reloading everything again?
Thanks.
I usually have my GridViews full of dynamic controls which can be a lot of "fun", if they're not recreated on PostBack they don't work.
You seem only interested in the SelectedRow but this solution will also work and help save you a headache if you start getting fancy with dynamic controls
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
gvObjects.DataSource = LoadCachedObjects();
gvObjects.DataBind();
}
private DataTable LoadCachedObjects()
{
var result = new DataTable();
if ((Session["CachedDataTable"] != null) && (IsPostBack))
{
//cached DataTable will only be used on PostBack
result = Session["CachedDataTable"] as DataTable;
}
if (result.Rows.Count == 0)
{
result = LoadObjects(); //Get data from the database
Session["CachedDataTable"] = result;
}
return result;
}
This only loads the data from the session when a postback event occurs, so you'll have one initial database hit on page load. Also if you end up using that code on other pages you don't have to be massively concerned about giving the session variable a unique name
By default the GridView selects a row based on Index. Try instructing the GridView to select rows based on Keys.
Set the EnablePersistedSelection property to true so that the row selection is based on data-key values. Now if your earlier selected row gets its index or position changed in any way it will remain selected.
If you can't prevent postbacks, you will obviously have to reload.
So the solution would be to try to reload as little as possible.
A good way is to cache data somewhere, for example in the Session object.
But only cache the primary keys together with a result index (1 to total result count). This way, you can quickly retrieve the primary keys that you need data for, and get only that data freshly from the database.
First of all, I am a new C# developer and I need some help please, I have a grid view with its SqlDataSource in my aspx file that contains 3 columns ID/Name/Job and several records(rows). When the user selects a row, I would like to redirect to another page and pass as a parameter the value of the selected ID of the row. Users are permitted to select only one row each time. I spent several hours on that however something strange is happened.
I have a method
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string selectedID;
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow gvr = e.Row;
selectedID = (GridView1.DataKeys[e.Row.RowIndex].Value.ToString());
gvr.Attributes.Add("OnClick","javascript:location.href='Views/EditMenus/EditCompany.aspx?id=" + selectedID + "'");
gvr.Attributes.Add("onmouseover", "this.style.backgroundColor='#FFE6E6'");
gvr.Attributes.Add("onmouseout", "this.style.backgroundColor=''");
gvr.Attributes.Add("style", "cursor:pointer;");
Session["IDs"] = selectedID;
} }
In my redirect page I have in page load method the following code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["IDs"] != null)
{
Label2.Text = "Selected ID is: "+ Session["IDs"].ToString();
}
}
Now, when I select a row, the redirection to the other page works correctly and the browser url has the correct value of the selected ID according the javascript code above, however the Label2.Text prints a wrong ID. Instead of the value of the selected ID, it prints the value ID of the last row of each page. Why that happens?
It's a bit strange for me since I am using the same variable "selectedID" for both cases as you can see above.
You need to sore value of your ID in Session variable on SelectedIndexChanged event of your GridView
void CustomersGridView_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
// Get the currently selected row.
//Because the SelectedIndexChanging event occurs before the select operation
//in the GridView control, the SelectedRow property cannot be used.
//Instead, use the Rows collection
//and the NewSelectedIndex property of the
//e argument passed to this event handler.
GridViewRow row = CustomersGridView.Rows[e.NewSelectedIndex];
//Cells[0] is for first column so assign according to your column for ID
Session["IDs"]=row.Cells[0].Text;
}
iv'e got an aspx page with some user controls , all of which contain a checkbox .
the checkbox is checked when the user control is added to the page.
the checkbox is set to auto post back
what i need is for when the auto post back occurs the user control will be gone.
first of all the way i load my user controls :
i load them as rows in a table and give their ID values the value of an entity that they represent
private void Load_Products(List<AppProduct> user_products)
{
HtmlTableRow row = null;
foreach(AppProduct p in user_products)
{
row = new HtmlTableRow();
tbl_products.Rows.Add(row);
CartProduct prd = (CartProduct)Page.LoadControl("~/UserControls/CartProduct.ascx");
prd.Title = p.Title;
prd.Price = p.Price.ToString();
prd.Pid = p.Pid.ToString();
prd.ID = p.Pid.ToString();
prd.State = 2;
prd.Product_Checked += new EventHandler(prd_Product_Checked);
HtmlTableCell cell = new HtmlTableCell();
cell.Controls.Add(prd);
row.Cells.Add(cell);
}
}
the CartProduct UserControl represents the AppProduct Entity
now the way i removed the product (usercontrol) was by removing it from the list as follows :
void prd_Product_Checked(object sender, EventArgs e)
{ // this removes the product from the same list that the load products function gets
ProductChangedEventArgs args = (ProductChangedEventArgs)e;
cart.RemoveProduct(uid, args.Pid);
Response.Redirect("~/Pages/cart.aspx");
}
now this works , but it seems wrong to have to postback and then redirect again in order to take affect the removal from the list occur's on the post back , but takes affect
only on the next page load, when the list is re-loaded .
if i could some how remove the item from the list during the page load of the post back
with out having to re-direct again.
any ideas how i could skip the redirect ?
i thought of maybe sending arguments with the postback but i don't know if that's even possible , cause then i could send the product id and remove it from the list before Load_Products is called .
thanks in advance
eran.
Instead of the Redirect why don't you simply call Load_Products again with the updated list of products?