ASP .NET RowUpdating GridView Troubles - c#

I'm having trouble with the RowUpdating Method. My GridView is connected to our local SQL Server, and I'm trying to update the data. Here is the code for the RowUpdating Method from MSDN.
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["TaskTable"];
//Update the values.
GridViewRow row = GridView1.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Description"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked;
//Reset the edit index.
GridView1.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
I get this error:
System.NullReferenceException: Object reference not set to an instance of an object.

try this code once.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
int id = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox tname = (TextBox)row.FindControl("nam");
TextBox tques = (TextBox)row.FindControl("que");
MySqlCommand cmd = new MySqlCommand("update exam set name1=#name,ques=#ques where id = #id", con);
cmd.Parameters.Add("#id", MySqlDbType.Int16).Value = id;
cmd.Parameters.Add("#name", MySqlDbType.VarChar, 30).Value = tname.Text.Trim();
cmd.Parameters.Add("#ques", MySqlDbType.VarChar,40).Value = tques.Text.Trim();
con.Open();
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
bind();
}

Not all GridViewRow have a DataItem.
You should add a if block around your code and verify the row being updated is of type DataRow.
if (e.Row.RowType == DataControlRowType.DataRow)
{
your code here...
}
More regarding RowTypes : http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.rowtype.aspx

public void bindGvEdit()
{
GridView1.DataSource = obj1.SelectAlltbl();
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindGvEdit();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindGvEdit();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
obj1.Id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
obj1.Name = ((TextBox)row.Cells[1].Controls[1]).Text;
obj1.Description = ((TextBox)row.Cells[2].Controls[1]).Text;
obj1.Updatetbl();
GridView1.EditIndex = -1;
bindGvEdit();
}

Related

How to store the value of a cell from grid view to database using the select command?

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow gv = GridView1.SelectedRow;
Session["m_email"] = gv.Cells[3];
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
string insert = "insert into Service_Info values(#c_email,#email,#first_name,#last_name,#contact,#licenseno,#street,#landmark,#pincode)";
SqlCommand cmd = new SqlCommand(insert, con);
cmd.Parameters.AddWithValue("#c_email", Session["user"].ToString());
cmd.Parameters.AddWithValue("#email",Session["m-email"].ToString());
cmd.Parameters.AddWithValue("#first_name", Session["user"].ToString());
cmd.Parameters.AddWithValue("#last_name", Session["user"].ToString());
cmd.Parameters.AddWithValue("#contact", Session["user"].ToString());
cmd.Parameters.AddWithValue("#licenseno", Session["user"].ToString());
cmd.Parameters.AddWithValue("#street", StreetText.Text);
cmd.Parameters.AddWithValue("#landmark", LandmarkText.Text);
cmd.Parameters.AddWithValue("#pincode", PincodeText.Text);
cmd.ExecuteNonQuery();
Label6.Visible = true;
Label6.Text = "Successfull...";
con.Close();
}
}
I want to store the value of a cell from the grid view to the database. I only want to store only the email cell value not all from grid view. But I am not getting a way to do so.
Try the following code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int selectedRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gv = GridView1.Rows[selectedRowIndex];
// Rest of the code
}
}

Gridview row in editing mode when I press "Insert" button? asp.net C#

I have a gridview and some control below the griview. I insert values from "control" and press "Insert" button then the values are inserted into the gridview row. Here is the gridview image when I insert values in control
and press the "Insert" button
and when I click on the "edit" button in griview the values of the selected edit row are displayed below the "controls" but when I update values in the control and click again "insert" then the row automatically edits the data, but I don't want this, I want that when I click on "insert" again that the row should not display in edit mode, here is the image
I want that when I click on "insert" button that the row values are replaced with new values.
Here is my aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", System.Type.GetType("System.Int32"));
dt.Columns.Add("Column Name", System.Type.GetType("System.String"));
dt.Columns.Add("Data Type", System.Type.GetType("System.String"));
dt.Columns.Add("Allow Null", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Primary Key", System.Type.GetType("System.Boolean"));
Session["MyDataTable"] = dt;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
DataRow row1 = t.NewRow();
row1["ID"] = t.Rows.Count + 1;
row1["Column Name"] = TextBox1.Text;
row1["Data Type"] = DropDownList1.Text;
row1["Allow Null"] = Null.Checked == true ? "true" : "false";
row1["Primary Key"] = Primary.Checked == true ? "true" : "false";
t.Rows.Add(row1);
Session["MyDataTable"] = t;
GridView2.DataSource = t;
GridView2.DataBind();
TextBox1.Text = String.Empty;
DropDownList1.Text = "Select DataType";
}
protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
t.Rows.RemoveAt(e.RowIndex);
GridView2.DataSource = t;
GridView2.DataBind();
}
protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
//GridView2.EditIndex = e.NewEditIndex;
// TextBox1.Enabled = true;
//GridViewRow row = GridView2.Rows[e.NewEditIndex];
TextBox1.Text = GridView2.Rows[e.NewEditIndex].Cells[2].Text.ToString();
DropDownList1.Text = GridView2.Rows[e.NewEditIndex].Cells[3].Text.ToString();
GridView2.DataSource = t;
GridView2.DataBind();
}
protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
GridView2.EditIndex = -1;
GridViewRow row = GridView2.Rows[e.RowIndex];
GridView2.DataSource = t;
GridView2.DataBind();
}
public void cancel(object sender, GridViewCancelEditEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
GridView2.EditIndex = -1;
GridViewRow row = GridView2.Rows[e.RowIndex];
GridView2.DataSource = t;
GridView2.DataBind();
}

search, edit and delete using gridview with sql server in c#

i am using Gridview buttons to edit and delet records from sql DB , the problem that i use specific criteris (search by textbox and combobox) then i do edit for the results here is the code i use :
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["zamzammembersConnectionString"].ConnectionString);
if (!IsPostBack)
{
bind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
TextBox textname = (TextBox)row.FindControl("textbox1");
TextBox textmarks = (TextBox)row.FindControl("textbox2");
GridView1.EditIndex = -1;
conn.Open();
SqlCommand cmd = new SqlCommand("update emp set marks=" + textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
public void bind()
{
conn.Open();
SqlCommand com = new SqlCommand("select zam_pcinfo.employe_name as Name , zam_location.locationname as Location from zam_pcinfo inner join zam_location on zam_pcinfo.location_id = zam_location.locationId where zam_pcinfo.employe_name like #name or zam_location.locationname like #locationname;", conn);
com.Parameters.AddWithValue("#name", SqlDbType.VarChar).Value = nametxt.Text;
com.Parameters.AddWithValue("#locationname", SqlDbType.VarChar).Value = locationdrop.SelectedValue;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
conn.Open();
SqlCommand cmd = new SqlCommand("delete emp where rowid=" + lbldeleteID.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind();
}
}
when i try to make the same code in bind() method to a button it works fine but i couldn't do edit and delete on it . how can i make edit and delete in gridview with data that i search for ?

Data not displaying out despite auto-selecting gridview row

I'm trying to let the gridview auto-select the first row of data upon page load. However, in the gridview, it shows that the first row is being highlighted
but no data is being displayed in my textbox. The data only appears when i click the select button in my gridview again.
This is how i added the auto-select gridview row in my page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvnric.SelectedIndex = 0;
}
}
This is how i get my data from my gridview to my textbox
protected void gvnric_SelectedIndexChanged(object sender, EventArgs e)
{
Session["nric"] = gvnric.SelectedRow.Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cm = new SqlCommand("Select fullname, contact, address, email From MemberAccount Where nric = '" + Session["nric"] + "'", con);
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
txtFullName.Text = dr["fullname"].ToString();
txtAddress.Text = dr["contact"].ToString();
txtContact.Text = dr["address"].ToString();
txtEmail.Text = dr["email"].ToString();
}
con.Close();
Image1.Attributes["src"] = "MemberNricCard.aspx?";
Image1.Attributes["height"] = "200";
Image1.Attributes["width"] = "200";
}
But what could possibly caused the data not to be displayed when the first row already being selected upon page load.
I would Re Factor the code as below :
PageLoad
if (!IsPostBack)
{
gvnric.SelectedIndex = 0;
LoadFormFields();
}
gvnric_SelectedIndexChanged
protected void gvnric_SelectedIndexChanged(object sender, EventArgs e)
{
LoadFormFields();
}
and create LoadFormFields with what you have in gvnric_SelectedIndexChanged
You can just call your gridview code in the page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvnric.SelectedIndex = 0;
gvnric_SelectedIndexChanged(this, EventArgs.Empty);
}
}

GridView does not change on page change

Gridview: Data does not change on page change.
Hi, im working on a asp.net website with c#.
I have a gridview with paging, the gridview is populated from an sql database, and on the PageIndexChanging I have:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BindGridControl();
gridView.PageIndex = e.NewPageIndex;
gridView.DataBind();
}
If I click on page 2 for example, the next rows of data display fine.
But if I click back to the page 1, the data does not change, it keep displaying the data from the page 2.
How can I solve this?
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
BindGridControl();
gridView.DataBind();
}
Is your BindGridControl() load the data and set it to your gridView datasource?
You can reverse order of instructions
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
BindGridControl();
gridView.DataBind();
}
I had this problem too for a long time.
I came up with this and it finally works for me.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BindGridControl(e.NewPageIndex);
}
And then in your BindGridControl function:
protected void BindGridControl(int pageNumber = 0)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings[connect‌​ion].ConnectionStrin‌​g);
SqlDataReader dr;
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = sqlConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_load";
sqlConn.Open();
dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.PageIndex = pageNumber;
GridView1.DataSource = dt;
GridView1.DataBind();
sqlConn.Close();
}
Try
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
BindGridControl();
DataBind();
}

Categories