When trying to update GridView data, it successfully runs, but it gets the old data instead of the data you type in the textboxes.
This is what I have:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
objLogic.UpdateContact(name, phone, email, contactId); //passes values to SQL to update database
GridView1.EditIndex = -1;
GridView1.DataBind();
}
and
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
and
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = objLogic.LoadClient();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "clientId";
DropDownList1.DataBind();
}
GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
GridView1.DataBind();
For example, the current data is:
name: Blake, phone: 123-234-3456, email: test#test.com, contactId: 22
I type in new data:
name: John, phone: 555-555-5555, email: test2#test2.com, contactId: 22
Data that ends up in the database:
name: Blake, phone: 123-234-3456, email: test#test.com, contactId: 22
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = objLogic.LoadClient();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "clientId";
DropDownList1.DataBind();
BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
GridView1.DataBind();
}
Every time the page posts back you are rebinding the grid. Move the binding of the grid into a separate function. After you do the row updating, rebind the grid.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
objLogic.UpdateContact(name, phone, email, contactId); //passes values to SQL to update database
GridView1.EditIndex = -1;
BindGrid();
}
When you edit you must call BindGrid too.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
//GridView1.DataBind(); this is meaningless, you have not set a DataSource
BindGrid();
}
When you raise the RowUpdating event your basically getting the values BEFORE the GridView updates the row. This is basically so you can cancel the update operation. To get what you've type in I think you need to get the new values (the Dictionary e.NewValues() in your case).
In your case you can use it something like this (assuming name, phone and email are what they're called in your gridview):
foreach(DictionaryEntry de in e.NewValues())
{
string name = de.FirstOrDefault(x => x.Key == "name").Value;
string phone = de.FirstOrDefault(x => x.Key == "phone").Value;
string email = de.FirstOrDefault(x => x.Key == "email").Value;
}
NOTE: If you're simply using this to get the values typed in to update your database then you're better of binding the datagrid and use the value after that to ensure you definitely have the same values in the datagrid as to what you put into the database. Alternatively, use the RowUpdated event instead of the RowUpdating event.
The most prevalent reason is that we usually forgot to check the postbacks in the Page Load event.
check the post-back, then the problem will be removed.
if (! IsPostBack)
{
readData();
...
}
Prokzy I have just your example on my side and doing something like this worked fine for me. notice the DataSource portion. I have a DataSet instantiated as aDataSet btw
protected void GridView1_GridViewPageEventArgs e(object sender, GridViewPageEventArgs e)
{
GridView1.EditIndex = e.NewPageIndex;
GridView1.DataSource = null;
GridView1.DataSource = aDataset;
GridView1.DataBind();
}
You need to call LoadContacts again and reassign GridView1.DataSource after the database is updated. Currently, the DataSource is not being updated - and is just using the collection that was retrieved prior to the row update.
Related
I'm trying to make some columns readonly for not being able to edit them. I have tried a lot of solutions but none of them worked.I am using a gridview without datasource.( I have more tables and i'm displaying them using a dropdownlist).Anyway i want to edit just 2 column or one and i can't do this.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//// this function doesn't work
BoundField bound = GridView1.Columns[0] as BoundField;
bound.InsertVisible = false;
bound.ReadOnly = true;
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
((BoundField)GridView1.Columns[1]).ReadOnly = true;//this doesn't work too
GridViewRow row = GridView1.Rows[e.RowIndex];
string contract_ID = (row.Cells[2].Controls[0] as TextBox).Text;
string room_ID= (row.Cells[6].Controls[0] as TextBox).Text;
string query = "UPDATE CONTRACTE_INCHIRIERE SET ID_CAMERA='"+room_ID+"' WHERE ID_CONTRACT="+contract_ID;
Response.Write(query);
using (OracleCommand cmd = new OracleCommand(query,con))
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
//Reset the edit index.
GridView1.EditIndex = -1;
//Bind data to the GridView control.
SortingBindGrid();
}
Try:
GridView1.ReadOnly = true;
Or this for a single cell:
GridView1.Rows[rowIndex][colName].ReadOnly = true;
i have created simple website asp.net webform using C#. i have code to display data in dropdownlist when page load like this:
private void DisplayData()
{
List<ListItem> items = new List<ListItem>();
items.Add(new ListItem("User", "1"));
items.Add(new ListItem("Administrator", "0"));
DropdownList1.DataSource = items;
DropdownList1.DataBind();
}
I call it in page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayData()
}
}
i try to get value from DropdownList1 in btnSubmit
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblResult.Text = DropdownList1.SelectedValue;
}
this result always get value User or Administartor string. but, it doesn't i want. I wanna get value just from the values in DropdownList1 as 0 or 1. How to do this?
One approach is to use the DropDownList SelectedItem Property to get the selectedItem(ListItem), then use the ListItem.Value Property to get the corresponding value for the ListItem.
lblResult.Text = DropdownList1.SelectedItem.Value; // Value property Gets or sets the value associated with the ListItem.
Try specifying DataValueField of DropDownList1:
DropdownList1.DataSource = items;
DropdownList1.DataValueField = "Value";
DropdownList1.DataTextField = "Text";
DropdownList1.DataBind();
Convert.ToInt32(DropdownList1.selectedItem.value);
I asked a similar question to this but the circumstances have changed.
I bind my gridview through code rather than on the source.
The pagination works fine, but if I click a button on second page of the gridview (after pagination), the postback is causing the pagination to reset to page 1. Can anyone tell me what I'm doing wrong?
Within my pageload i have set the !POSTBACK method as shown i.e if there is postback event, then it shouldn't reset the grid but it does!
Heres the onload:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["usersName"] != null)
{
object a = Session["_id"];
IDMaster = Convert.ToInt32(a);
GridView1.Columns[10].Visible = true;
GridView1.Columns[11].Visible = true;
}
else
{
GridView1.Columns[10].Visible = false;
GridView1.Columns[11].Visible = false;
}
if (!IsPostBack)
{
BindGrid();
}
The BindGrid();
SqlConnection sqlcon = new SqlConnection(connstring);
SqlCommand sqlcmd = new SqlCommand("select * from Coffees ORDER BY coffeeName ASC", sqlcon);
SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
Page index method:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
if(ViewState["searchTerm"] != null)
{
object a = ViewState["searchTerm"];
string reloadTerm = a.ToString();
setGrid(reloadTerm);
}
You need to bind your gridview in GridView1_PageIndexChanging event
GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
if(ViewState["searchTerm"] != null)
{
object a = ViewState["searchTerm"];
string reloadTerm = a.ToString();
setGrid(reloadTerm);
}
BindGrid();
}
hopefully it works for you.
Since you are binding grid view dynamically, Please remove
if (!IsPostBack)
condition from page load. Grid view needs binding every time.
I found this issue. I forgot that after I add an item to my cart i was calling response.redirect to refresh the page....obviously this meant the page was recalled refreshing the page so the grid was always going to reset. Thanks again.
i am getting the data from gridview on rowcommand event by the following code
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "editproject")
{
string rowindex = e.CommandArgument.ToString();
int index = int.Parse(rowindex);
GridViewRow row = GridView2.Rows[index];
Label6.Text = row.Cells[1].Text;
}
}
but it would give only the data of the field that is visible in gridview row .how can i get the field that is not visible but bound to the gridview.
You can't get the value that you set to invisible because these were not rendered at the client side and can't be grabbed on the server side.
Alternatively you can store the value in hidden field and then you can get it from hidden field.
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show(dataGridView1.SelectedRows[0].Cells[0].Value.ToString ());
}
You can,t get the invisible bound elements but you can get the value from data source .For example you save data in data table which assigned to grid .Store this data table in view-state and on row command get data-key of that row and retrieved value through data table
You can get a command-like button which is invisible in the gridview, just look at this:---
False visibility of button requires you to have changed the property EnableEventValidation="False" on the page directive in default.aspx
private void grd_bind()
{
SqlDataAdapter adp = new SqlDataAdapter("select* from tbbook", ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lk = (LinkButton)(e.Row.Cells[5].Controls[0]);
e.Row.Attributes["Onclick"] = ClientScript.GetPostBackClientHyperlink(lk, "");
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = GridView1.SelectedRow.Cells[0].Text;
TextBox2.Text = GridView1.SelectedRow.Cells[1].Text;
TextBox3.Text = GridView1.SelectedRow.Cells[2].Text;
TextBox4.Text = GridView1.SelectedRow.Cells[3].Text;
TextBox5.Text = GridView1.SelectedRow.Cells[4].Text;
}
then in the default.aspx page, set EnableEventValidation
<%# Page Language="VB" EnableEventValidation="false" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
I have populated a list box using a Data-table.
In another method, I have to retrieve the data table from the list box.
Datatable dt = (DataTable)lstExample.DataSource;
Throws an error, that the Datatable dt is null
I am working on c# ASP.Net
If you are trying to do this on a Postback then the DataTable will no longer be there. You will need to save it in ViewState or Session if you want access to it on a Postback, or just hit the database again.
For example:
protected override Page_Load(object sender, EventArgs e)
{
if( !IsPostBack)
{
DataTable tbl = GetData();
lstData.DataSource = tbl;
lstData.DataBind();
// store in viewstate
ViewState["data"] = tbl;
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
DataTable tbl = (DataTable)ViewState["data"];
}