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();
}
}
Related
I'm having a trouble with my code.
I'm trying to have the user the ability to submit his email to subscribe to my "notify me" service, I havn't code anything lately so I a bit confused..
I'm trying to Insert, Read, and Update data in my Online SQL Server.. but nothing seems to work! I don't know why I tried everything I know I check a million times it seems good.
Plus if there is any errors my catch should show it to me but even that doesn't work :(
Take a look at this maybe your eyes will see something I don't see.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["notifyCS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
try
{
string checkEmail = "SELECT User_Email FROM tbl_users WHERE User_Email = #User_Email";
string checkSubscription = "SELECT User_Status FROM tbl_users WHERE User_Email = #User_Email";
string submitEmail = "INSERT INTO tbl_users (User_UID, User_Email, User_Status) VALUES (#User_UID, #User_Email, #User_Status)";
string submitEmail2 = "UPDATE tbl_users SET User_UID = #User_UID, User_Status = #User_Status WHERE User_Email = #User_Email";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
SqlDataAdapter emailSDA = new SqlDataAdapter
{
SelectCommand = emailCMD
};
DataSet emailDS = new DataSet();
emailSDA.Fill(emailDS);
//if there is no email registered.
if (emailDS.Tables[0].Rows.Count == 0)
{
SqlCommand registerEmail = new SqlCommand(submitEmail, conn);
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail.ExecuteNonQuery();
registerEmail.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
else if (emailDS.Tables[0].Rows.Count > 0)
{
using (SqlCommand checkSub = new SqlCommand(checkSubscription, conn))
{
checkSub.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
SqlDataReader sdr = checkSub.ExecuteReader();
if (sdr.HasRows)
{
string res = sdr["User_Status"].ToString();
if (res != "subscribed")
{
using (SqlCommand registerEmail2 = new SqlCommand(submitEmail2, conn))
{
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail2.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail2.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail2.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail2.ExecuteNonQuery();
registerEmail2.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
}
else
{
conn.Close();
conn.Dispose();
Response.Redirect("index.aspx");
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
}
}
Try it this way:
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
string checkEmail = "SELECT * FROM tbl_users WHERE User_Email = #User";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
emailCMD.Parameters.Add("#User", SqlDbType.NVarChar).Value = email.Text;
SqlDataAdapter da = new SqlDataAdapter(emailCMD);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
DataTable emailRecs = new DataTable();
emailRecs.Load(emailCMD.ExecuteReader());
DataRow OneRec;
if (emailRecs.Rows.Count == 0)
{
OneRec = emailRecs.NewRow();
emailRecs.Rows.Add(OneRec);
}
else
{
// record exists
OneRec = emailRecs.Rows[0];
}
// modify reocrd
OneRec["User_UID"] = User_UID;
OneRec["User_Email"] = email.Text;
OneRec["User_Status"] = "subscribed";
email.Text = null;
da.Update(emailRecs);
}
}
Basically, what I want to delete an entry form a dataviewtable which pulls data through from MySql. I thought this would be done fairly by effectively copying the modify code and substituting it for 'DELETE'. However, from the code below, you can clearly see that hasn't worked. I will copy most of my code for you:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HNR3NJB\\mysql;Initial Catalog=stock;Integrated Security=True");
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
con.Open();
sqlQuery = #"DELETE FROM [Products] WHERE [ProductID] = '" + textboxProductID.Text + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
MessageBox.Show("Record doesn't exist!", "ERROR:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Reading Data
LoadData();
}
So that's the delete button's code now for the add button and load data function
Add button:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//insert logic
con.Open();
if(textboxProductID.Text == "" || textboxProductName.Text == "")
{
MessageBox.Show("You have to enter either a product ID or product name", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
bool status = false;
if (comboboxStatus.SelectedIndex == 0)
{
status = true;
}
else
{
status = false;
}
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
sqlQuery = #"UPDATE [Products] SET [ProductName] = '" + textboxProductName.Text + "' ,[ProductStatus] = '" + status + "' WHERE [ProductID] = '" + textboxProductID.Text + "'";
}
else
{
sqlQuery = #"INSERT INTO [Stock].[dbo].[Products] ([ProductID],[ProductName],[ProductStatus]) VALUES
('" + textboxProductID.Text + "','" + textboxProductName.Text + "','" + status + "')";
}
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
textboxProductID.Clear();
textboxProductName.Clear();
LoadData();
}
}
LoadData function:
public void LoadData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//reading data from sql
SqlDataAdapter sda = new SqlDataAdapter("Select * From [stock].[dbo].[Products]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["ProductID"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
if ((bool)item["ProductStatus"])
{
dataGridView1.Rows[n].Cells[2].Value = "Active";
}
else
{
dataGridView1.Rows[n].Cells[2].Value = "Deactive";
}
}
}
You're going to need the IfProductsExists method too:
private bool IfProductsExists(SqlConnection con, string productCode)
{
SqlDataAdapter sda = new SqlDataAdapter("Select 1 From [Products] WHERE [ProductID]='" + productCode + "'", con);
DataTable dt = new DataTable();
if (dt.Rows.Count > 0)
return true;
else
return false;
}
It's going to be an inventory system that's going to be used at work for the sale and inventory management of IT equipment.
im using the following code to populate a Gridview.I add 2 buttons for editing and deleting at the end.Hook to the click event.. but after i add the delete
button the click events are not firing.What im i doing wrong?
private void BindGrid2()
{
try
{
string constr = "Data Source=INSPIRE-1;" +
"Initial Catalog=testdatabase;" +
"User id=testuser;" +
"Password=tester;";
using (SqlConnection con = new SqlConnection(constr))
{
string commandText = "SELECT invnumber,itemname,quantity,rate FROM mytable2 where invnumber= #name";
using (SqlCommand command = new SqlCommand(commandText, con))
{
command.Parameters.AddWithValue("#name", text_inv.Text);
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView2.DataSource = dt;
}
}
}
if (flag2 == false)
{
flag2 = true;
DataGridViewButtonColumn uninstallButtonColumn = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Edit";
uninstallButtonColumn.Text = "Edit";
dataGridView2.Columns.Insert(0, uninstallButtonColumn);
dataGridView2.Columns[0].DisplayIndex = 4;
DataGridViewButtonColumn uninstallButtonColumn2 = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Delete";
uninstallButtonColumn.Text = "Delete";
dataGridView2.Columns.Insert(5, uninstallButtonColumn2);
dataGridView2.Columns[5].DisplayIndex = 5;
}
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
string orderId;
if (e.ColumnIndex == 4)
{
try
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value;
using (SqlConnection conn = new SqlConnection(constr))
{
try
{
conn.Open();
SqlDataReader myReader = null;
string commandText = "select * from mytable2 where invnumber= #name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("#name", text_inv.Text);
myReader = command.ExecuteReader();
while (myReader.Read())
{
text_cname.Text = myReader["cname"].ToString();
text_quantity.Text = myReader["quantity"].ToString();
text_item.Text = myReader["itemname"].ToString();
text_rate.Text = myReader["rate"].ToString();
dateTimePicker1.Text = myReader["date"].ToString();
// textBox4.Text = myReader["stock"].ToString();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
catch (Exception error)
{
}
}
else if (e.ColumnIndex == 5)
{
using (SqlConnection conn = new SqlConnection(constr))
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value;
conn.Open();
SqlDataReader myReader = null;
string commandText = "delete from mytable2 where invnumber= #name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("#name", text_inv.Text);
myReader = command.ExecuteReader();
}
BindGrid2();
}
}
Corrections below
dataGridView2.Columns.Insert(5, uninstallButtonColumn2) to dataGridView2.Columns.Insert(1, uninstallButtonColumn2)
if (e.ColumnIndex == 4) to if (e.ColumnIndex == 0)
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value; to orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[2].Value; at both the places
else if (e.ColumnIndex == 5) to else if (e.ColumnIndex == 1)
I have a windows form of controls combobox and datetimepicker..
I have given null or empty to combobox in page load..
so combobox shows empty intially while loading database values to it in windows form..
but the problem is
because of the datetimepicker is not kept to null or empty my form is showing message box as "the day is already existed" before form is desplaying..here my code follows
I want to show that message after combobox value is selected..
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name from Employee_Details", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("employee_id", typeof(string));
dt.Columns.Add("employee_name", typeof(string));
dt.Load(dtr);
comboBox1.DisplayMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = null;
if(comboBox1.SelectedItem == null)
{
txtemployeeid.Text = "";
txtemployeename.Text = "";
}
cn.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("select employee_id,Employee_name from Employee_Details where employee_name=('" + comboBox1.Text + "')", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
if (dtr.Read())
{
string employee_id = (string)dtr["employee_id"];
string employee_name = (string)dtr["employee_name"];
txtemployeeid.Text = employee_id;
txtemployeename.Text = employee_name;
dtr.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
if (comboBox1.SelectedItem != null)
{
try
{
string dtp = dateTimePicker1.Value.ToString("dd/MM/yyyy");
SqlCommand cmd1 = new SqlCommand("select date from dailyattendance where date=('" + dtp + "') and employee_id='" + txtemployeeid.Text + "' and empployee_name='" + txtemployeename.Text + "' ", cn);
SqlDataReader dtr1;
dtr1 = cmd1.ExecuteReader();
if (dtr1.Read())
{
string date = (string)dtr1["date"];
if (dtp == date)
{
MessageBox.Show("this day is already existed");
}
}
dtr1.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
cn.Close();
}
can any one solve it please..Thanx in advance
You can simply use dtr.Text="";
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();
}