My delete function is not removing entries and is being ignored - c#

I am having problems getting my delete function to work in my ASP.net (C#) web application and I really have no idea where to go next.
The function is called on button clicked but it is as if the Page_Load method is completely ignoring the command. I'm new to this and would appreciate some help.
Thanks.
Here is the Page_load, the DisplayData method, the Count method and the delete method which is called from a button click.
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection cn;
static int count = 1;
static int max = 2;
static String sqlQuery = "Select * from Footballer";
static bool firstTime = true;
protected void Page_Load(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\David\\Desktop\\WebApplication5\\WebApplication5\\App_Data\\Database2.mdf\";Integrated Security=True";
cn = new SqlConnection(str);
SqlCommand command = cn.CreateCommand();
cn.Open();
mycount();
if (firstTime == true)
{
displayData();
firstTime = false;
}
}
protected void mycount()
{ // count no of els in table
max = 0;
var cmd = cn.CreateCommand();
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
while (reader.Read()) max++;
reader.Close();
}
protected void displayData()
{
var cmd = cn.CreateCommand();
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
for (int i = 0; i < count; i++)
reader.Read();
TextBox1.Text = "" + reader[0];
TextBox2.Text = "" + reader[1];
TextBox5.Text = "" + reader[2];
TextBox6.Text = "" + reader[3];
TextBox7.Text = "" + reader[4];
TextBox8.Text = "" + reader[5];
reader.Close();
}
protected void deleteData()
{
var cmd = cn.CreateCommand();
string query = "DELETE FROM [Footballer] WHERE [PlayerName] = #name";
cmd.CommandText = query;
string name = TextBox4.Text;
cmd.Parameters.AddWithValue("#name", name);
cmd.ExecuteNonQuery();
}
}

From the code, it looks like Textbox4 value is getting overwritten before the Delete, Page_load will get called for each postback including button click event. The flag bool firstTime = true doesn't work for the purpose you are trying to achieve. I believe you want to load text box data only when the page loads first time. so you should modify the Page_load event to use IsPostBack property instead of firstTime flag, like below.
protected void Page_Load(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\David\\Desktop\\WebApplication5\\WebApplication5\\App_Data\\Database2.mdf\";Integrated Security=True";
cn = new SqlConnection(str);
SqlCommand command = cn.CreateCommand();
cn.Open();
mycount();
if(!IsPostBack)
{
displayData();
}
}
This will ensure that, TextBox4 value entered by you in UI won't get overwritten when you click delete button and delete code should work as expected

Don't open the connection in Page_Load only open it where needed. Also use using to properly dispose of your resources.
public partial class WebForm1 : System.Web.UI.Page
{
//You should really pull this from your web.config
string connectionString = "(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\David\\Desktop\\WebApplication5\\WebApplication5\\App_Data\\Database2.mdf\";Integrated Security=True";;
static int count = 1;
static int max = 2;
static String sqlQuery = "Select * from Footballer";
static bool firstTime = true;
protected void Page_Load(object sender, EventArgs e)
{
mycount();
if (firstTime == true)
{
displayData();
firstTime = false;
}
}
protected void mycount()
{ // count no of els in table
max = 0;
using(SqlConnection con = new SqlConnection(connectionString))
{
con.open();
using(var cmd = cn.CreateCommand())
{
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
while (reader.Read()) max++;
reader.Close();
}
}
}
protected void displayData()
{
using(SqlConnection con = new SqlConnection(connectionString))
{
con.open();
using(var cmd = cn.CreateCommand())
{
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
for (int i = 0; i < count; i++) reader.Read();
TextBox1.Text = "" + reader[0];
TextBox2.Text = "" + reader[1];
TextBox5.Text = "" + reader[2];
TextBox6.Text = "" + reader[3];
TextBox7.Text = "" + reader[4];
TextBox8.Text = "" + reader[5];
reader.Close();
}
}
}
protected void deleteData()
{
//Add A break point here to ensure the method is hit
using(SqlConnection con = new SqlConnection(connectionString))
{
con.open();
using(var cmd = cn.CreateCommand())
{
string query = "DELETE from [Footballer] where [PlayerName] = #name";
cmd.CommandText = query;
string name = TextBox4.Text;
//When stepping through in debug mode, make sure
//name is what you expect.
cmd.Parameters.AddWithValue("#name", name);
cmd.ExecuteNonQuery();
}
}
}
Note, I've done all this in the SO editor so I may have missed some closing }

Related

updated values are not getting stored in the textbox

protected void Page_Load(object sender, EventArgs e)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
//Button click function
protected void Button1_Click(object sender, EventArgs e)
{
cn.Open();
st = "update patient_db set address ='" + TextBox1.Text + "' ,phone=" + TextBox2.Text+"where unique_id=123";
cmd = new SqlCommand(st, cn);
int result2 = cmd.ExecuteNonQuery();
if (Convert.ToBoolean(result2))
{
result1.Text = "details updated successfully";
}
cn.Close();
}
After assigning the value to textbox from the database,if I type some other new value in the text box,it is not taking the new value,it still persists with the old value.May i know the reason and solution for this? thanks in advance
Write a method LoadData, move the code from page_load into this method. Then call this method from page_load wrapped in a if(!IsPostBack)-check. Call this method also from the button-click event handler after you've updated the values.
private void LoadData()
{
using (var cn = new SqlConnection("Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True"))
{
cn.Open();
using(var cmd = new SqlCommand("select * from patient_db where unique_id = 123", cn))
using (var dr = cmd.ExecuteReader())
{
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
LoadData();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// ... update
LoadData();
}
Important notes:
Also use the using-statement for every object implementing IDisposable like the connection or the datareader. On that way all unmanaged resources are disposed properly. Even in case of an error.
If 123 is just an example and actually is a value provided by the user use sql-parameters to prevent sql-injection. No, use them always.
Add IsPostBack control at Page_Load method. Because before Button_Click event Page_Load event firing.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
}
You need to check page.Ispostback property in your page Load.
Here is your code.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
}
When you click on button then it will first call PageLoad event. So it will again set your old value to textbox and then it will call update method. So Update method will update old value to database.

datatable won't update

I wanted to update my database that contains two text and one filename that is needed for image.
The problem is that the image and filename updates but the two other text values title and body wont be affected and don't change the previous values. Also visual studio don't get any problem and the message for executing command shows that it's executed the command but nothing except the image changes.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
Response.Redirect("~/default.aspx");
if (Request .QueryString ["action"]=="edit")
{
Panel1.Visible = true;
}
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString =GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString () + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text=myReader ["Title"].ToString ();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
protected void btn_addpost_Click(object sender, EventArgs e)
{
string title= title_txt .Text ;
string body=bodytxt .Text ;
if (Request.QueryString["edit"] != null)
{
string message;
string filename = thumb_uploader.FileName;
string path = HttpContext.Current.Server.MapPath("~") + "\\Thumb";
string exup = System.IO.Path.GetExtension(thumb_uploader.FileName);
string[] ext = { ".jpg", ".png", ".jpeg" };
if (Array.IndexOf(ext, exup) < 0)
{
message = "not correct.";
}
if (thumb_uploader.FileBytes.Length / 1024 > 400)
{
message = "not currect.";
}
while (System.IO.File.Exists(path + "\\" + filename + exup))
{
filename += "1";
}
savepath = path + "\\" + filename;
if (thumb_uploader.HasFile)
{
thumb_uploader.SaveAs(savepath);
thumb = thumb_uploader.FileName;
SqlCommand command;
SqlDataAdapter da;
SqlConnection con3 = new SqlConnection();
con3.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
command = new SqlCommand();
command.Connection = con3;
da = new SqlDataAdapter();
da.SelectCommand = command;
command.CommandText = "UPDATE tbl_post SET Title=#title ,Body=#body ,Thumb=#thu Where Postid=" + Request.QueryString["edit"].ToString();
con3.Open();
command.Parameters.AddWithValue("#title", title );
command.Parameters.AddWithValue("#body", body );
command.Parameters.AddWithValue("#thu", thumb_uploader .FileName);
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
else
{
using (SqlConnection con3 = new SqlConnection(GNews.Properties.Settings.Default.connectionstring))
{
string sql = "update tbl_post SET Title=#title ,Body=#body Where Postid=#postid" ;
using (SqlCommand command = new SqlCommand(sql, con3))
{
con3.Open();
command.Parameters.AddWithValue("#title", title);
command.Parameters.AddWithValue("#body", body);
command.Parameters.AddWithValue("#postid", Request.QueryString["edit"].ToString());
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
}
}
}
I've found the answer I needed this code to include my pageload reading database so it wouldn't do it when I click on the update button.I mean the problem was all about the post back thing.
if (!Page.IsPostBack)
{
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString() + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text = myReader["Title"].ToString();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
}

Getting next row of table of access database every time on clicking a button

I am trying to get next rows from the table of access database but I am getting last row all time.
Please guide me how to loop through all rows?
Here is the code:
protected void btn_clk(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; DataSource=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
while(i<=count)
{
string cmdstr = "select * from table where id = " + i;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
con1.Close();
}
=It`s must outside a button click:
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
con1.Close();
Its must inside button click. You must make i property of form
if(i<=count)
{
string cmdstr = "select * from table where id = " + i;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
But i think it`s may rewrite to more beauty solve.
Sounds like you are after something like
private int _currentRecordId = -1;
...
string cmdStr = String.Format("SELECT * FROM Table WHERE id > {0} ORDER BY id LIMIT 1", _currentRecordId);
using (var con = new OleDbConnection(constr))
using (var com = new OleDbCommand(cmdStr, con))
{
con.Open();
using(var reader = com.ExecuteReader())
{
while (reader.Read())
{
_currentRecordId = reader.GetInt32(0); // whatever field the id column is
// populate fields
}
}
}
On first call this will retrieve the first record with an ID > -1. It then records whatever the ID is for this record so then on the next call it will take the first record greater than that e.g. if the first record is id 0 then the next record it will find is 1 and so on...
This only really works if you have sequential IDs of course.
Assuming that your table is not big (meaning it contains a manegeable number of records) you could try to load everything at the opening of your form and store that data in a datatable.
At this point the logic in your button should simply advance the pointer to the record to be displayed.
private DataTable data = null;
private int currentRecord = 0;
protected void form_load(object sender, EventArgs e)
{
using(OleDbConnection con1 = new OleDbConnection(constr))
using(OleDbCommand cmd = new OleDbCommand("select * from table", con1))
{
con1.Open();
using(OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
data = new DataTable();
da.Fill(data);
}
DisplayCurrentRecord();
}
}
private void DisplayCurrentRecord()
{
label1.Text = String.Format("{0}", data.Rows[currentRecord][1]);
RadioButton1.Text = String.Format("{0}", data.Rows[currentRecord][2]);
RadioButton2.Text = String.Format("{0}", data.Rows[currentRecord][3]);
RadioButton3.Text = String.Format("{0}", data.Rows[currentRecord][4]);
RadioButton4.Text = String.Format("{0}", data.Rows[currentRecord][5]);
}
protected void btn_clk(object sender, EventArgs e)
{
if(currentRecord >= data.Rows.Count - 1)
currentRecord = 0;
else
currentRecord++;
DisplayCurrentRecord();
}
Keep in mind that this is just an example. Robust checking should be applied to the rows (if they contains null values) and if there are rows at all in the returned table. Also, this is a poor man approach to the problem of DataBindings in WinForm, so perhaps you should look at some tutorials on this subject
Hope your table is not really named Table, that word is a reserved keyword for Access
simply remove the for loop to fetch record one by one
int lastFetchedRecordIndex=2;
protected void btn_clk(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
string cmdstr = "select * from table where id = " + lastFetchedRecordIndex;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
lastFetchedRecordIndex++;
con1.Close();
}

I want to check the username is already exists in my database table or not?

i have registration page and i want to check that username is already exist in database or not in 3 tier architecture.
MyRegistration.cs:
public static int checkusername(string user_txt)
{
int id2 = 0;
string selectstr = "select * from xyz where UserName = '" + user_txt + " ' ";
id2 = DataAccessLayer.ExecuteReader(selectstr);
return id2;
}
and the code behind onclick event of textbox:
protected void txt_username_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txt_username.Text))
{
int id = xyz.checkusername(txt_username.Text.Trim());
if (id > 0)
{
lblStatus.Text = "UserName Already Taken";
}
else
{
lblStatus.Text = "UserName Available";
}
}
}
DataAccessLayer:
public static int ExecuteReader(string Query)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = Query;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
id++;
}
cmd = null;
reader.Close();
con.Close();
return id;
}
I have edited some of your codes try like below... it will help you...
Text change Event :
protected void txt_username_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txt_username.Text))
{
if (xyz.checkusername(txt_username.Text.Trim()))
{
lblStatus.Text = "UserName Already Taken";
}
else
{
lblStatus.Text = "UserName Available";
}
}
}
Check Username :
public bool CheckUsername(string user_txt)
{
bool Result;
Result = DataAccessLayer.ExecuteReader(user_txt);
return Result;
}
Excute Reader :
public bool ExecuteReader(string user_txt)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
SqlCommand cmd = new SqlCommand("select * from xyz where UserName = #UserID", con);
SqlParameter param = new SqlParameter();
param.ParameterName = "#UserID";
param.Value = user_txt;
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
return true;
else
return false;
}
Usually if the "select query" doesn't find a userName with the parameter user_txt you'll id2 will be end up with the value -1. So the appropriate code would be:
if (id ==-1)
{
lblStatus.Text = "UserName Available";
}
if (id>0)
{
lblStatus.Text = "UserName Already Taken";
}
By the way, your code is highly insecure and your database can be easily attacked using SQL Injection I'd recommend you to understand this issue and add parameters to the query to prevent it. C# has its ways to implement this. Don't try to fix the access to the database, just start from scrath keeping in mind SQL Injection.
As others have mentioned, this approach has potentially serious security issues.
However, your problem may lie here user_txt + " ' ". The spaces around the second ', specifically the one before it may lead to the usernames not matching as expected.

checkBox in gridView doesn't update my table

I am using the following the code to populate table on clicking upon the checkbox but there is no change in table
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkUpdate = (CheckBox)
GridView1.Rows[i].Cells[0].FindControl("chkSelect");
if (chkUpdate != null)
{
if (chkUpdate.Checked)
{
string strID = GridView1.Rows[i].Cells[1].Text;
SqlCommand cmd;
string str1 = "update app1 set p_id=0 where p_id='" + strID + "'";
cmd = new SqlCommand(str1, con);
cmd .ExecuteNonQuery ();
}
}
}
}
Try this code it works
foreach (GridViewRows gdrv in GridView1.Rows)
{
CheckBox chkUpdate = (CheckBox)
gdrv.FindControl("chkSelect");
if (chkUpdate != null)
{
if (chkUpdate.Checked)
{
string strID = gdrv.Cells[1].Text;
SqlCommand cmd;
string str1 = "update app1 set p_id=0 where p_id='" + strID + "'";
cmd = new SqlCommand(str1, con);
con.open();
cmd .ExecuteNonQuery ();
con.close();
}
}
}
I'm guessing you really don't have a space in cmd .ExecuteNonQuery ();
When debugging, can you step into the if(chkUpdate.Checked) block?
I think the only problem in the query is the "Where" condition... if the p_id is Int type then you don't have to use ''...
So the statement must be :
string str1 = "update app1 set p_id=0 where p_id=" + strID;

Categories

Resources