Grid not updating on edit button press - c#

I have a gridview.
I am trying to edit it, but value is not getting updated.
My Code:
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
private void BindGrid()
{
try
{
da = new SqlDataAdapter("select * from emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
string eName = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='" + eName + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
GridView1.EditIndex = -1;
}
catch (Exception ex)
{
}
finally
{
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
}
Please let me know the point where i am making mistake.

use BindGrid() inside Page.IsPostBack as follows on Page_Load event
if(!Page.IsPostBack)
{
BindGrid();
}
Edit 1
I think the following line should work
BindGrid();
GridView1.EditIndex = -1;
As it is not working see is there any error in the catch block.
catch (Exception ex)
{
Response.Write(ex.Message);
}
See weather there is some error or not?

You can try like this...becuase...when you click on edit button your pageload event is called first....and on pageload you bind the gridview again...so its edit index is lost because it binded again...and it set edit index to -1 each and everytime...
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
}
Edit1: OP After Update Edit Mode Doesnt goes..
You Have to Set gridview Edit index before Its binding like below....
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='" + eName + "'", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;//Put this line Before the Binding of GridView
BindGrid();
}

Related

Attempting to get a count of records from gridview based on a selected date from dropdownlist but cant?

The problem lies that upon selection of the date in the dropdown it will give the count of the LAST selection, not the current.
I am a novice and the only thing I can think of is some type of postback issue? The gridview populates fine with the records selected by the DDL, so I just cant get my head around why the count that is rendered is the previous selection.
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e)
{
lblRecordCounter.Text = "";
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT (*) FROM gescdb" +
"WHERE ClassDate=" + ddlClassDate.Text, conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
GridRegistrants.DataSource = reader;
GridRegistrants.DataBind();
reader.Close();
}
catch
{
}
finally
{
conn.Close();
lblRecordCounter.Text = GridRegistrants.Rows.Count.ToString();
}
In your Page_Load method you do the same, right? You have to move that code into following block:
if (!IsPostBack){
//Your code is here
}
Your DropDownList:
<asp:DropDownList ID="ddlClassDate" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlClassDate_SelectedIndexChanged" />
Your code behind:
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
BindDDL();
BindGrid(ddlClassDate.SelectedValue);
}
}
protected void BindDDL(){
//Bind Your dropdownlist here
}
protected void BindGrid(string ddate){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString);
SqlCommand comm = new SqlCommand("select * from gescdb where ClassDate = #date", conn);
comm.Parameters.Add("#date", SqlDbType.VarChar).Value = ddate;
try
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
sda.Fill(ds);
GridRegistrants.DataSource = ds;
GridRegistrants.DataBind();
}
catch
{
//...
}
finally
{
conn.Close();
}
}
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e){
BindGrid(ddlClassDate.SelectedValue);
}

Gridview loses edit index when value is searched

There is a textbox which searches the value from the Gridview. When the value displays then Every time I click Edit it goes to the first Index Row of the Gridview. I want to only edit the row which has been searched by ID.
For example if I search a value that is in row 8. It displays row 8 which is fine but when I click edit it goes to first row again. Why is this happening?
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
protected void BindGridView()
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from tblInventory", con);
con.Open();
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("select * from tblInventory where (Part like '%" + txtSearch.Text + "%') or (Brand like '%" + txtSearch.Text + "%' )", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
TextBox Part = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPart");
TextBox Description = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDescription");
TextBox Qty = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtQty");
DropDownList Brand = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlBrand");
TextBox ItemType = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtItemType");
SqlCommand cmd = new SqlCommand("update tblInventory set Part='" + Part.Text + "',Description='" + Description.Text + "',Qty='" + Qty.Text + "',Brand='" + Brand.Text + "',ItemType='" + ItemType.Text + "' where ID=" + id, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
You need to modify your BindGridView Method, it will take care the problem.
Now when you a search a value in any Row and it displays the results, and when edit is clicked, it will stay on the selected Row.
txtSearch is just the ID of your Search TextBox.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView(this.txtSearch.Text);
}
}
protected void BindGridView(string column1)
{
SqlCommand cmd = new SqlCommand("select * from table1 where (column1 like '%" + txtSearch.Text + "%')", con);
con.Open();
cmd.Parameters.AddWithValue("#column1 ", column1 );
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindGridView(this.txtSearch.Text);
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView(this.txtSearch.Text);
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView(this.txtSearch.Text);
}

asp.net datalist update to another page

I am using datalist in asp.net c#, to display data from database and perform delete. But also at this table I have an other button "edit" which I want to get the id of item and go to another page with a form that is prefilled with data about that item. The problem is that I am new at asp.net and I dont know how to get data form one page to another (like id).
public partial class DataList : System.Web.UI.Page
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
try
{
if(!IsPostBack)
{
Bind();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
public void Bind()
{
SqlConnection con = new SqlConnection(connection);
SqlDataAdapter da = new SqlDataAdapter("select * from artikulli", con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
con.Close();
datalist2.DataSource = ds.Tables[0];
datalist2.DataBind();
}
protected void Datalist1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
SqlConnection conn = new SqlConnection(connection);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "Insert into artikulli(tema) values (#tema)";
command.Parameters.Add("#tema", SqlDbType.VarChar, 250).Value = txtTema.Text;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
}
}
protected void Datalist1_EditCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Edit"))
{
Response.Redirect("EditArtikull3.aspx");
}
}
protected void datalist1_CancelCommand(object source, DataListCommandEventArgs e)
{
datalist2.EditItemIndex = -1;
Bind();
}
protected void datalist1_UpdateCommand(object source, DataListCommandEventArgs e)
{
if(e.CommandName.Equals("Update"))
{
}
}
protected void datalist2_DeleteCommand(object source, DataListCommandEventArgs e)
{
Label lblId = e.Item.FindControl("lblId") as Label;
SqlConnection conn = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "Delete from artikulli where id=#id";
cmd.Parameters.Add("#id", SqlDbType.Int, 11).Value = lblId.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Bind();
}
}
I really need some help
One of the easiest ways to pass data is through the QueryString. Consider for example..
Label lblId = e.Item.FindControl("lblId") as Label;
string id=lblId.Text;
Response.Redirect("EditArtikull3.aspx?id="+id);
Then on the EditArtikull3 page, in the Page_Load method, check for that QueryString parameter and load data accordingly.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
if(!String.IsNullOrEmpty(Request.QueryString["id"]))
{
string id=Request.QueryString["id"];
//load data based on the id
}
else
{
//tell the user they can't navigate directly to this page.
}
}
}
Pass it as querystring eg
Response.Redirect("EditArtikull3.aspx?Id=yourId");
You can refer to
http://msdn.microsoft.com/en-us/library/vstudio/6c3yckfw(v=vs.100).aspx
One alternative would be to pass the id in the URL as in:
protected void Datalist1_EditCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Edit"))
{
Response.Redirect(string.Format("EditArtikull3.aspx?id={0}",((DataRowView)e.Item.DataItem).Row.ItemArray[0].ToString()); // where [0] is the index of the column containing the item ID
}
}
Then on the EditArtikull3.aspx page read it from the QueryString
Page_Load(...)
{
if(!IsPostback)
{
string id = Request.QueryString["id"] as string;
if(id!=null)
{
//query the database and populate the data
}
}
}
Query string method:
Response.Redirect("EditArtikull3.aspx?id=yourId");
In redirected page..
protected void Page_Load(object sender, EventArgs e)
{
string id=Request.QueryString["id"];
}

System.IndexOutOfRangeException : Cannot find table 0

I am trying to implement a button_click event in C# such that if the button is pressed, the gridview is filled with the query results but am getting the above error.
This is the code:
public partial class Pages_Managingpayment : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyServer"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
Load();
}
}
protected void Load() {
DataSet ds = new DataSet();
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No records on display";
}
protected void SearchButton_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from users", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string passwords = GridView1.DataKeys[e.RowIndex].Value.ToString();
TextBox pass = (TextBox)GridView1.Rows[e.RowIndex].FindControl("Password");
TextBox usernames = (TextBox)GridView1.Rows[e.RowIndex].FindControl("username");
TextBox usertypes = (TextBox)GridView1.Rows[e.RowIndex].FindControl("usertype");
con.Open();
SqlCommand cmd = new SqlCommand("update users set User_Type='" + usertypes.Text + "',Username='" + usernames.Text + "' where password='" + passwords + "'", con);
cmd.ExecuteNonQuery();
con.Close();
//.ForeColor = Color.Green;
//lblresult.Text = username + " Details Updated successfully";
GridView1.EditIndex = -1;
BindEmployeeDetails();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindEmployeeDetails();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["UserId"].ToString());
string passwords = GridView1.DataKeys[e.RowIndex].Values["password"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from users where password='" + passwords + "'", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
// lblresult.ForeColor = Color.Red;
//lblresult.Text = username + " details deleted successfully";
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox usertypes = (TextBox)GridView1.FooterRow.FindControl("usertype");
TextBox usernames = (TextBox)GridView1.FooterRow.FindControl("username");
TextBox passwords = (TextBox)GridView1.FooterRow.FindControl("password");
con.Open();
SqlCommand cmd =
new SqlCommand(
"insert into users values('" + usertypes.Text + "','" +
usernames.Text + "','" + passwords.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
// lblresult.ForeColor = Color.Green;
//lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
//lblresult.ForeColor = Color.Red;
//lblresult.Text = txtUsrname.Text + " Details not inserted";
}
}
}
I guess here is an error in the code:
DataSet ds = new DataSet();
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
ds will not contain tables and therefore contain no Table[0]. It would be helpful though if you could break your code down to a few lines in which the error occurs.
In the Load() method you create a new DataSet and try to access it's non-existing table with the code ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());.
Try creating a new DataTable and adding it to the DataSet before binding it the GridView (Example Here).
And also, when you call the Load() method, make the condition if(!IsPostBack) as in:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Load();
}
}
Make sure you check the index before you use table or Row. I have modified your Load method and hope you can modify other places to correct the mistakes.
protected void Load() {
DataSet ds = new DataSet();
if(ds.Tables.Count == 0)
{
// Syntax might be wrong. I am trying to add new table if it is missing.
ds.Table.Add(new Table());
}
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No records on display";
}

Couldn't get the values from the cells in GridView using check box in ASP.net

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
rdr.Close();
}
catch
{
conn.Close();
}
}
I have a button like this. But I'm not able to get the values of the cells(Label is not getting appended).
protected void Button1_Click(object sender, EventArgs e)
{
string[] FID={};
int j=0;
foreach (GridViewRow di in GridView1.Rows)
{
HtmlInputCheckBox chkBx = (HtmlInputCheckBox)di.FindControl("CheckBox1");
if ( chkBx != null && chkBx.Checked)
{
FID[j] += di.Cells[2].Text;
j++;
Label1.Text += di.Cells[2].Text;
//Label lbl = (Label)di.FindControl("Id");
//Response.Write(lbl.Text + "<br>");
}
}
}
Put your page load code under if(!IsPostBack){yourCode....} so when you click the button your page load event will be called before the click handler and it will rebind the gridview.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
rdr.Close();
}
catch
{
conn.Close();
}
}
}
i think if you can debug the code,
you can find and solve your problem easily.
First, check is your loop really do.
Second, is Cell[2] is really what you want to get data.(I doubt that)
Hope it works!

Categories

Resources