search, edit and delete using gridview with sql server in c# - 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 ?

Related

choose name from dropownlist and associated ID appear in textbox

this is my code for populating a dropdown list with customers name.
protected void Page_Load(object sender, EventArgs e)
{
//Creating a connection to my database using the connection string
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
{
SqlCommand cmd = new SqlCommand("Select CustomerName from Customer", con);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
DropDownList1.DataTextField = "CustomerName";
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
}
}
}
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
}
}
I want to be able too; when this name is chosen from the dropdownlist box , the associated customer ID will appear in a textbox.
thanks!
It should be as simple as this, by the looks of it:
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue
}
Assuming you have a textbox whose ID is TextBox1.
Alternatively if you want to display the text from the dropdown list (as opposed to the ID value), then simply:
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedItem.Text
}

Get more information on GridView row click

I need to get this : When I click on a row, to get a more information about that particular file(every row represents one file from database), and that information is stored in different table... So, how is the best way to do this? Here you have a picture...
public partial class WebForm1 : System.Web.UI.Page
{
Web_service.WebService1SoapClient service;
protected void Page_Load(object sender, EventArgs e)
{
service = new Web_service.WebService1SoapClient();
BindData();
}
protected void BindData()
{
string strConnection = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select * from request", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow r in GridView1.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
r.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
r.Attributes["onmouseout"] = "this.style.textDecoration='none';";
r.ToolTip = "Click to select row";
r.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + r.RowIndex, true);
}
}
base.Render(writer);
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
}
}

try to print on BIXOLON SRP-350plusII, but it can't get my design right

i have a task to do on "POS" system, instead the old system witch was VB 6.0 and Access, i try to make a new one with SQL Server, ADO.NET and C#, so i try to print bills out of BIXOLON printer, but when i design my report it doesn't appear correct, it looks like this:
here is some shots of my test project (this isn't my real project, its just testing)
Some code:
private void ID()
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("SELECT Max(ID)+1 FROM Info", cn);
cmd.ExecuteNonQuery();
int i = Convert.ToInt32(cmd.ExecuteScalar());
textBox1.Text = i.ToString();
}
catch
{
textBox1.Text = "1";
}
cn.Close();
}
private void LoadGrid()
{
dataGridView1.DataSource = null;
dataGridView1.Rows.Clear();
SqlDataAdapter ADAP = new SqlDataAdapter("Select * from Info", cn);
DataSet DS = new DataSet();
ADAP.Fill(DS, "Info");
dataGridView1.DataSource = DS.Tables["Info"];
textBox2.SelectAll();
textBox2.Focus();
}
private void Insert()
{
if (textBox2.Text != "")
{
SqlCommand cmd;
cn.Open();
cmd = new SqlCommand("INSERT INTO Info (Name, Date) VALUES (#Name, #Date)", cn);
cmd.Parameters.AddWithValue("#Name", textBox2.Text.Trim());
cmd.Parameters.AddWithValue("#Date", DateTime.Now.ToString());
cmd.ExecuteNonQuery();
cn.Close();
}
else
{
MessageBox.Show("Empty!");
textBox2.Focus();
}
}
private void Delete()
{
SqlCommand cmd = new SqlCommand("DELETE Info WHERE ID = #ID", cn);
cn.Open();
cmd.Parameters.AddWithValue("#ID", textBox1.Text);
cmd.ExecuteNonQuery();
cn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'infoDataSet1.Info' table. You can move, or remove it, as needed.
this.InfoTableAdapter.Fill(this.infoDataSet1.Info);
LoadGrid();
ID();
this.reportViewer1.RefreshReport();
this.reportViewer1.RefreshReport();
}
private void button3_Click(object sender, EventArgs e)
{
LoadGrid();
}
private void button2_Click(object sender, EventArgs e)
{
Insert();
LoadGrid();
ID();
textBox2.Focus();
textBox2.Text = "";
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Insert();
LoadGrid();
ID();
textBox2.Focus();
textBox2.Text = "";
}
}
private void button1_Click(object sender, EventArgs e)
{
Delete();
LoadGrid();
ID();
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows.Count != 0)
{
button1.Enabled = true;
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
textBox2.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
}
}
private void button4_Click(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'infoDataSet1.Info' table. You can move, or remove it, as needed.
this.InfoTableAdapter.Fill(this.infoDataSet1.Info);
this.reportViewer1.RefreshReport();
}
}
now i need help to make it out like this:
set Margin to 0 all around(left, right, top, bottom)

How to make a bit false when user select checkbox in gridview

Hi coder i have a search user page where i have a texbox, button and a gridview. Now when i enter name of the user and click on search button i get the detail of the user.
My database is like this
I already bind my gridview on page load so that i can also view the details of user in gridview like this:
Now in this gridview you can see a IsEnable header which have checkbox control. That Enable is a bit which is always true when user is created.
What i want is when user click on that checkbox that bit become false i try this on the rowdatabound but it give me object reference error can you guys tell me what i do to make my bit false when user select that checkbox
Please help me on this thanks in advance
Now this what i done now with my code now tell me how to update my enable bit from true to false on row update
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.GetGridData();
}
}
protected void BindGrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from CreateUser", 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";
}
}
private void GetGridData()
{
con.Open();
string query = "Select * from CreateUser";
da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void btnSearchUser_Click(object sender, EventArgs e)
{
this.BindGrid();
}
protected void lnkdelete_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
//getting particular row linkbutton
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
//getting userid of particular row
int UserID = Convert.ToInt32(GridView1.DataKeys[gvrow.RowIndex].Value.ToString());
string FirstName = gvrow.Cells[0].Text;
con.Open();
SqlCommand cmd = new SqlCommand("delete from CreateUser where UserID=" + UserID, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindGrid();
//Displaying alert message after successfully deletion of user
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + FirstName + " details deleted successfully')", true);
this.GetGridData();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//if (e.Row.RowType == DataControlRowType.DataRow)
//{
// //getting username from particular row
// string FirstName = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "FirstName"));
// //identifying the control in gridview
// LinkButton lnkbtnresult = (LinkButton)e.Row.FindControl("lnkdelete");
// //raising javascript confirmationbox whenver user clicks on link button
// lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + FirstName + "')");
//}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GetGridData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label userid= (Label)row.FindControl("lblUserID");
con.Open();
SqlCommand cmd = new SqlCommand("delete FROM CreateUser where UserID='" + Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString()) + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
string query = string.Empty;
string userid = GridView1.DataKeys[e.RowIndex].Values["UserID"].ToString();
//Label id = GridView1.Rows[e.RowIndex].FindControl("lblUserID") as Label;
TextBox FirstName = GridView1.Rows[e.RowIndex].FindControl("txtFirstName") as TextBox;
TextBox LastName = GridView1.Rows[e.RowIndex].FindControl("txtLastName") as TextBox;
TextBox DomainID = GridView1.Rows[e.RowIndex].FindControl("txtDomainID") as TextBox;
TextBox EmailID = GridView1.Rows[e.RowIndex].FindControl("txtEmailID") as TextBox;
TextBox Password = GridView1.Rows[e.RowIndex].FindControl("txtPassword") as TextBox;
TextBox ConfirmPassword = GridView1.Rows[e.RowIndex].FindControl("txtConfirmPassword") as TextBox;
TextBox RoleType = GridView1.Rows[e.RowIndex].FindControl("txtRoleType") as TextBox;
CheckBox IsEnable = GridView1.Rows[e.RowIndex].FindControl("chkIsEnableEdit") as CheckBox;
//TextBox textadd = (TextBox)row.FindControl("txtadd");
//TextBox textc = (TextBox)row.FindControl("txtc");
GridView1.EditIndex = -1;
con.Open();
//SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
SqlCommand cmd = new SqlCommand("update CreateUser set FirstName='" + FirstName.Text + "',LastName='" + LastName.Text + "',DomainID='" + DomainID.Text + "',EmailID='" + EmailID.Text + "',Password='" + Password.Text + "',ConfirmPassword='" + ConfirmPassword.Text + "',RoleType='" + RoleType.Text + "',Enable='" + IsEnable.Checked + "' where UserID='" + userid + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
//GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
}
Put some defensive coding in first, and find out where the object reference error is happening:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var chk = (CheckBox)e.Row.FindControl("chkEnable");
if (chk == null || !chk.checked) return;
var userId =GridView1.DataKeys[row.RowIndex].Value as string;
if (string.IsNullOrWhiteSpace(userId)) return;
var query = "update CreateUser set Enable='False' where UserID='" + userid + "'";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
}
}
You can use the CheckChanged event:
<asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkEnable" runat="server" AutoPostBack="true" OnCheckedChanged="ChkEnable_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And then update the database in CheckChanged event:
protected void ChkEnable_CheckedChanged(object sender, EventArgs e)
{
int selRowIndex = ((GridViewRow)(((CheckBox)sender).Parent.Parent)).RowIndex;
var userId = gridView.DataKeys[selRowIndex].Value as string;
if (string.IsNullOrWhiteSpace(userId)) return;
var checkBox = gridView.Rows[selRowIndex].FindControl("chkEnable") as CheckBox;
if (checkBox == null) return;
var query = "update CreateUser set Enable= #Enabled where UserID='" + userid + "'";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("Enabled", checkBox.Checked);
cmd.ExecuteNonQuery();
con.Close();
}
First of all why are you doing it on RowDataBound event ? RowDataBound occurs when a row is
bounded to gridview but here we have to update gridview rows.
If you have to update your rows you can do it on RowUpdating command .
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Checkbox chkbx = ((Checkbox)(row.Cells[8].Controls[0]));
bool IsChecked =chkbx.Checked ;
//You can write your update command here.
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox MyName= (TextBox)e.Row.FindControl("FirstName");
string name = Myname.text;
//For checkbox
Checkbox chkbx = (Checkbox)e.Row.FindControl("IsEnabled");
if(chkbx.Checked ==true)
{
// do your stuff for checkbox checked.
}
else
{
// do your stuff if checkbox is not selected
}
}
}
Finally i got my answer thanks for your reply guys
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.GetGridData();
}
}
protected void BindGrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from CreateUser", 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";
}
}
private void GetGridData()
{
con.Open();
string query = "Select * from CreateUser";
da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void btnSearchUser_Click(object sender, EventArgs e)
{
this.BindGrid();
}
protected void lnkdelete_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
//getting particular row linkbutton
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
//getting userid of particular row
int UserID = Convert.ToInt32(GridView1.DataKeys[gvrow.RowIndex].Value.ToString());
string FirstName = gvrow.Cells[0].Text;
con.Open();
SqlCommand cmd = new SqlCommand("delete from CreateUser where UserID=" + UserID, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindGrid();
//Displaying alert message after successfully deletion of user
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + FirstName + " details deleted successfully')", true);
this.GetGridData();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GetGridData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label userid= (Label)row.FindControl("lblUserID");
con.Open();
SqlCommand cmd = new SqlCommand("delete FROM CreateUser where UserID='" + Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString()) + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
string query = string.Empty;
string userid = GridView1.DataKeys[e.RowIndex].Values["UserID"].ToString();
//Label id = GridView1.Rows[e.RowIndex].FindControl("lblUserID") as Label;
TextBox FirstName = GridView1.Rows[e.RowIndex].FindControl("txtFirstName") as TextBox;
TextBox LastName = GridView1.Rows[e.RowIndex].FindControl("txtLastName") as TextBox;
TextBox DomainID = GridView1.Rows[e.RowIndex].FindControl("txtDomainID") as TextBox;
TextBox EmailID = GridView1.Rows[e.RowIndex].FindControl("txtEmailID") as TextBox;
TextBox Password = GridView1.Rows[e.RowIndex].FindControl("txtPassword") as TextBox;
TextBox ConfirmPassword = GridView1.Rows[e.RowIndex].FindControl("txtConfirmPassword") as TextBox;
TextBox RoleType = GridView1.Rows[e.RowIndex].FindControl("txtRoleType") as TextBox;
CheckBox IsEnable = GridView1.Rows[e.RowIndex].FindControl("chkIsEnableEdit") as CheckBox;
//TextBox textadd = (TextBox)row.FindControl("txtadd");
//TextBox textc = (TextBox)row.FindControl("txtc");
GridView1.EditIndex = -1;
con.Open();
//SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
SqlCommand cmd = new SqlCommand("update CreateUser set FirstName='" + FirstName.Text + "',LastName='" + LastName.Text + "',DomainID='" + DomainID.Text + "',EmailID='" + EmailID.Text + "',Password='" + Password.Text + "',ConfirmPassword='" + ConfirmPassword.Text + "',RoleType='" + RoleType.Text + "',Enable='" + IsEnable.Checked + "' where UserID='" + userid + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
//GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
}

ASP .NET RowUpdating GridView Troubles

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();
}

Categories