Gridview Edit Delete and Update in ASP.NET - c#

I tried Implementing the code for Edit and Update button for gridview but it doesn't seems working for me. Add button working well but delete and update do not working. During runtime error the error is "An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: Unknown column 'p001' in 'where clause'"
Note: type of P_Id in the database is varchar(10), name varch(100), level varchar, value varchar
public partial class ManagePractice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
TextBox txtID = (TextBox)GridView1.FooterRow.FindControl("txtID");
TextBox txtSubject = (TextBox)GridView1.FooterRow.FindControl("txtSubject");
RadioButtonList Level = (RadioButtonList)GridView1.FooterRow.FindControl("RadioButtonList2");
RadioButtonList PType = (RadioButtonList)GridView1.FooterRow.FindControl("RadioButtonList1");
AddPractice(txtID.Text.Trim(), txtSubject.Text.Trim(), Level.Text.Trim(), PType.Text.Trim());
BindData();
}
private void AddPractice(string P_Id, string subject, string level, string type)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "insert into practice(P_Id,name,level,value) values ('" + P_Id + "','" + subject + "','" + level + "','" + type + "')";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
private void BindData()
{
DataTable dt = new DataTable();
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
MySqlDataAdapter adp = new MySqlDataAdapter("select P_Id,level,name,value from practice", cn);
adp.Fill(dt);
}
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = (GridView1.DataKeys[e.RowIndex].Value.ToString ());
DeletePractice(id);
BindData();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox txtID = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtID");
TextBox txtSubject = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSubject");
// TextBox Level1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtlevel");
// TextBox PType1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPType1");
RadioButtonList Level = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList2");
RadioButtonList PType = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList1");
UpdatePractice( txtID.Text , txtSubject.Text, Level.Text, PType.Text);
GridView1.EditIndex = -1;
BindData();
}
private void UpdatePractice( string P_Id, string name, string level, string value)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "UPDATE practice SET P_Id='" + P_Id + "',name='" + name + "',level='" + level + "',value='" + value + " WHERE P_Id=" + P_Id + "";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
private void DeletePractice(string id)
{
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
string query = "DELETE FROM practice WHERE P_Id=" + id + "";
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}

First sight:
Since P_Id column has VARCHAR(10) datatype, I figured out you forget to include some additional apostrophes on UPDATE & DELETE clause. The correct form of SQL statements should be this (notice additional apostrophe signs around P_Id column):
string query = "UPDATE practice SET P_Id='" + P_Id + "',name='" + name + "',level='" + level + "',value='" + value + "' WHERE P_Id= '" + P_Id + "'";
and
string query = "DELETE FROM practice WHERE P_Id='" + id + "'";
Only string values require apostrophes around them, numbers do not.

Related

why i get this error when i do allow paging True The data source does not support server-side data paging

I had opened a related topic before, but I realized the problem now. When I set allow paging correctly in the properties of gridview in web form.aspx, I get this error. I don't know if the codes I wrote in aspx.cs browser cause this problem, please help
'''
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=MERIH-PC;Initial Catalog=aspidus;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GVbind();
}
}
void clear()
{
txtName.Text = "";
txtPhone.Text = "";
txtAdd.Text = "";
}
protected void btnInsert_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO [dbo].[idus] VALUES ('" + txtName.Text + "', '" + txtPhone.Text + "', '" + txtAdd.Text + "')", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
Response.Write("<script>alert('Data inserted successfully') </script>");
con.Close();
}
GVbind();
clear();
}
//protected void btnDelete_Click(object sender, EventArgs e)
//{
// SqlCommand cmd = new SqlCommand(#"DELETE FROM [dbo].[idus]
// WHERE [ID]='" + txtID.Text + "'", con);
// con.Open();
// cmd.ExecuteNonQuery();
// Response.Write("Data deleted successfully");
// con.Close();
//}
//protected void btnUpdate_Click(object sender, EventArgs e)
//{
// SqlCommand cmd = new SqlCommand(#"UPDATE [dbo].[idus]
// SET[ID] = '" + txtID.Text + "',[name] = '" + txtName.Text + "',[phone] = '" + txtPhone.Text + "',[address] = '" + txtAdd.Text + "' WHERE [ID]= '" + txtID.Text + "'", con);
// con.Open();
// cmd.ExecuteNonQuery();
// Response.Write("Data updated successfully");
// con.Close();
//}
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GVbind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
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 address = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
con.Open();
SqlCommand cmd = new SqlCommand("update [dbo].[idus] set name='" + name + "', phone='" + phone + "', address='" + address + "' where ID = '" + ID + "'", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
con.Close();
Response.Write("<script>alert('Data has been updated') </script>");
GridView1.EditIndex = -1;
GVbind();
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GVbind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
con.Open();
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
SqlCommand cmd = new SqlCommand("delete from [dbo].[idus] where ID='" + id + "'", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
con.Close();
Response.Write("<script>alert('Data has been deleted') </script>");
GridView1.EditIndex = -1;
GVbind();
}
}
protected void DisplayData()
{
SqlConnection con = new SqlConnection("Data Source=MERIH-PC;Initial Catalog=aspidus;Integrated Security=True");
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from [dbo].[idus]", con);
con.Open();
da.Fill(dt);
con.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GVbind();
'''
enter image description here
enter image description here
You are assigning the GV a "reader", and you can't use a reader - you have to fill a table, or use some other ennumberable collection. Say like a data table.
So, this code:
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
Change to :
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
Datatable dt = new dt();
dt.load(cmd.ExecuteReader());
GridView1.DataSource = dt;
GridView1.DataBind();
}
So, while you can "shove" the GV to a reader directly? If you going to use paging, then you can't shove into the GV a reader - since paging does not work with a non innumerable type of data set (like a reader).
So, just load up a data table. And note how I did not even need a data adaptor to load up a data table (the data table has a .Load command for you. (so, you can shorten your other code this way also).

Insert and Update Function work on single button click in c#

I am trying to insert and update data using same button. I have created method(uniqueEmail()) to check the email address exist in table or not. Using this method I am trying to insert data if email is not preset.
here is my code please correct me where I am going wrong.
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail()==true)
{
cmd.CommandText = "update registeruser set email='" + TextBox1.Text + "', password='" + TextBox2.Text + "' where email='" + TextBox1.Text + "'";
}
else
{
cmd.CommandText = "insert into registeruser values('" + TextBox1.Text + "', '" + TextBox2.Text + "')";
}
cmd.ExecuteNonQuery();
con.Close();
}
public bool uniqueEmail()
{
string stremail;
string querye = "select count(email) as email from registeruser";
SqlCommand cmd = new SqlCommand(querye, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
stremail = dr["email"].ToString();
return(stremail != "0");
if (stremail != "0")
{
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
}
You need to check for the count of the particular emailId, not the total count.
Modify the code as below:
public static bool uniqueEmail(string email)
{
string stremail;
string querye = "select count(email) as email from register where
email = '" + email + "'";
//Remaining Code
}
public static void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail(TextBox1.Text)) == true)
//Remaining Code
}
#nirmala you should replace method
public void EmailCheck()
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from EmailSignUp where EmailId= #EmailId", con);
cmd.Parameters.AddWithValue("#EmailId", this.txtEmail.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("EmailId = " + dr[5].ToString() + " Already exist");
txtEmail.Clear();
break;
}
}
}
Two Things need to be done
Pass the Email Id while calling
if (uniqueEmail()==true)
To
if (uniqueEmail(TextBox1.Text)==true)
And in uniqueEmail method chenage the query ()include where condition as below
public bool uniqueEmail(email)
{
string stremail;
string querye = "select count(email) as email from registeruser where email='" + email + "'";
//your remaining code
}
Hi Nirmala your code is correct only you need to put where clause to find the email id already exist in the Database.
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail()==true)
{
cmd.CommandText = "update registeruser set email='" + TextBox1.Text + "', password='" + TextBox2.Text + "' where email='" + TextBox1.Text + "'";
}
else
{
cmd.CommandText = "insert into registeruser values('" + TextBox1.Text + "', '" + TextBox2.Text + "')";
}
cmd.ExecuteNonQuery();
con.Close();
}
public bool uniqueEmail()
{
string stremail;
string querye = "select count(email) as email from registeruser where email = '" +TextBox1.Text+ "'";
SqlCommand cmd = new SqlCommand(querye, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
stremail = dr["email"].ToString();
return(stremail != "0");
if (stremail != "0")
{
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
}

When entering data does not update the text box

Hello friends I am writing to pull information from the base TextBox and I want to update the database through the TextBox , but when I enter the new value is the old value does not always save the new value
Code behind
protected void Page_Load(object sender, EventArgs e)
{
string ID = Request.QueryString["Id"].ToString();
SqlConnection baglan = new SqlConnection(ConnectionString3);
baglan.Open();
SqlCommand com = new SqlCommand("Select * from pkategori where Id='" + ID + "'", baglan);
SqlDataReader oku = com.ExecuteReader();
if (oku.Read())
{
baslik.Text = oku["Tanim"].ToString();
detaylar.Text = oku["Detaylar"].ToString();
}
else
{
baslik.Text = "Bulunmadı";
}
}
Button Click Event
string ust = Request.QueryString["ID"].ToString();
SqlConnection baglanti = new SqlConnection(ConnectionString3);
baglanti.Open();
string kayit = "update pkategori set Tanim=#Tanim where Id=#Id";
SqlCommand komut = new SqlCommand(kayit, baglanti);
komut.Parameters.AddWithValue("#Tanim", baslik.Text);
komut.Parameters.AddWithValue("#Id", ust);
komut.ExecuteNonQuery();
baglanti.Close();
Simple, just wrap your code in Page_Load in a !IsPostBack-check:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string ID = Request.QueryString["Id"].ToString();
SqlConnection baglan = new SqlConnection(ConnectionString3);
baglan.Open();
SqlCommand com = new SqlCommand("Select * from pkategori where Id='" + ID + "'", baglan);
SqlDataReader oku = com.ExecuteReader();
if (oku.Read())
{
baslik.Text = oku["Tanim"].ToString();
detaylar.Text = oku["Detaylar"].ToString();
}
else
{
baslik.Text = "Bulunmadı";
}
}
}
Otherwise you are loading the text from the database and the changed value is overwritten.

Object reference not set to an instance of an object for asp.net

protected void Page_Load(object sender, EventArgs e)
{
lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ProfileCS"].ConnectionString;
string sql = "Select password from Profile where userid = '" + Session["userid"] + "'";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr; // to hold reference of datareader returned
//prepare a place - datatable to hold the data
DataTable dt = new DataTable();
//setting up command
cmd.CommandText = sql;
cmd.Connection = con;
//connection and execute command
con.Open();
dr = cmd.ExecuteReader();
dt.Load(dr); // copy data from datareader to datatable
string pwdcheck;
pwdcheck = dt.Rows[0]["password"].ToString();
if (tb_verify.Text.Equals(pwdcheck))
{
string password = tb_pwd.Text;
sql = "Update Profile set password ='" + password + "'";
sql = sql + "where userid = '" + Session["userid"] + "'";
cmd.CommandText = sql;
cmd.Connection = con;
try
{
cmd.ExecuteNonQuery();
lb_msg.Text = "Password changed succesfully";
}
catch (Exception ex)
{
lb_msg.Text = "Problems encountered " + ex.Message;
}
finally
{
con.Close();
con.Dispose();
cmd.Dispose();
}
}
else
lb_msg.Text = "Old password Incorrect";
}
protected void lblClick(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Session.Clear(); // This may not be needed -- but can't hurt
Session.Abandon();
FormsAuthentication.RedirectToLoginPage();
}
}
lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";
there is an error at the line above with
Object reference not set to an instance of an object the change password feature was working before.
In your case Session["userid"] must be NULL,handle it

can not Update data in C# Database Access

I have a problem with the button3 it's the UPDATE BUTTON, The message box keeps saying it's a syntax error in the UPDATE Statement. And also if I create another listbox, if I insert a new data, it does not make me insert another data in the 2nd listbox. So if I insert something on the 1st listbox, that index would, for example, be 9, then I would try to insert on the next listbox, but then it would proceed to the index 10.
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
private void listBox2_Click(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != 1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
textBox2.Text = listBox2.SelectedItem.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
string q = "insert into Table1 (name) values ('"+textBox1.Text.ToString()+"')";
doSomething(q);
textBox1.Text = null;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
string q = "delete from Table1 where id=" + listBox1.SelectedItem.ToString();
doSomething(q);
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox2.Text != "" & listBox1.SelectedIndex != -1)
{
string q = "update Table1 set (name) '" + textBox2.Text.ToString() + "' where id " + listBox1.SelectedItem.ToString();
doSomething(q);
textBox2.Text = "";
}
}
private void doSomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Problem 1: you are missing = Symbol while providing input parameters.
Try This:
string q = "update Table1 set [name]= '" + textBox2.Text.ToString() + "' where id= " + listBox1.SelectedItem.ToString();
Problem 2: you are not assigning connection object to `OleDbCommand.
Add This: before executing command
cmd.Connection=cn;
Complete Code:
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
private void listBox2_Click(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if(l.SelectedIndex!=-1)
textBox2.Text = l.SelectedItem.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
string q = "insert into Table1(name) values ('"+textBox1.Text.ToString()+"')";
doSomething(q);
textBox1.Text = null;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
string q = "delete from Table1 where id=" + listBox1.SelectedItem.ToString();
doSomething(q);
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox2.Text != "" & listBox1.SelectedIndex != -1)
{
string q = "update Table1 set [name] ='" + textBox2.Text.ToString() + "' where id =" + listBox1.SelectedItem.ToString();
doSomething(q);
textBox2.Text = "";
}
}
private void doSomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.Connection=cn;
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Suggestion : your query is open to SQL injection attacks , i would suggest to use Parameterised Queries to avoid them.
Using Parameterised Queries :
private void doSomething(String q)
{
try
{
cn.Open();
cmd.CommandText = "update Table1 set [name]=#name where id=#id";
cmd.Parameters.AddWithValue("#name",textBox2.Text.ToString());
cmd.Parameters.AddWithValue("#id",listBox1.SelectedItem.ToString());
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
string q = "update Table1 set (name) '" + textBox2.Text.ToString() + "' where id " + listBox1.SelectedItem.ToString();
In the above code (btn3) your are missing id =
Write code like this :
string q = "update Table1 set (name) '" + textBox2.Text.ToString() + "' where id=" + listBox1.SelectedItem.ToString();
UPDATE :
My Access query function:
public void ExecuteAccessQurey(string _pQurey)
{
OleDbConnection con = new OleDbConnection("DatabaseConnectionString");
OleDbCommand cmd = new OleDbCommand(_pQurey, con);
if (con.State == System.Data.ConnectionState.Closed)
{
con.Open();
}
cmd.ExecuteNonQuery();
con.Close();
}

Categories