Update DB with updated Textbox Information in C# - c#

Trying to update the first name of the student there is a textbox "FirstNameTextbox" information was loaded to it from the DB, when I change the information in the textbox and try to write the changes it read only the original data.So if it loaded "Craig" as the first name from the DB, i would edit and put "Chris" in the textbox, what happens is that Craig is written to the DB and not "Chris"
int stuID = getSqlStuID(IDNUMLabel.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
string sqlUpdateStudent = "Update tblStudent set fname = #fname where stuID = #stuID";
SqlCommand cmd = new SqlCommand(sqlUpdateStudent, conn);
conn.Open();
cmd.Parameters.AddWithValue("#stuID", stuID);
cmd.Parameters.AddWithValue("#fname", FirstNameTextbox.Text);
cmd.ExecuteNonQuery();
ErrorMessage.Text = "Success";
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
IDNUMLabel.Text = Session["User"].ToString();
getStuData(Session["User"].ToString());
}
else
{
Response.Redirect("../Login/Login.aspx");
}
}
private void getStuData(string id)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select fname, sname From tblStudent Where idnumber = '" + id + "' ";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader selectedRecord = cmd.ExecuteReader();
cmd.CommandType = CommandType.Text;
while (selectedRecord.Read())
{
FirstNameTextbox.Text = selectedRecord["fname"].ToString();
LastNameTextbox.Text = selectedRecord["sname"].ToString();
}
selectedRecord.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
//id = 0;
//string msg = "Error reading Student ID";
//msg += ex.Message;
//throw new Exception(msg);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}

At what point do you make the actual update? After a button was pressed, after the value was entered on the textbox...? You're missing the method in which the code that handles the update is placed...
Maybe this could help: How to display data from database into textbox, and update it

Related

Textbox data is not adding to the database

I'm currently practicing to make a barcode attendance application. After scanning the barcode, the barcode is automatically showing in a text box. There is a add button to send the barcode to the database. But when I click the add button only a blank dataset is adding.(It's working when directly type in the textbox)
private void VideoCaptureDevice_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
BarcodeReader reader = new BarcodeReader();
var result = reader.Decode(bitmap);
if (result != null)
{
textBox1.Invoke(new MethodInvoker(delegate ()
{
textBox1.Text = result.ToString();
}));
}
pictureBox1.Image = bitmap;
}
Here is the add button code
private void button1_Click(object sender, EventArgs e)
{
cmd = new MySqlCommand();
cmd.CommandText = "insert into student_att (`id`, `nic`, `name`, `address`, `number`, `batch`) select* from student_dt where nibm_id like '" + textBox1.Text + "%'";
if (textBox1.Text == "")
{
MessageBox.Show("Please provide all data");
}
else
{
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted");
string Query = "select * from student_att ;";
MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
dataGridView2.DataSource = dTable;
}
try
{
textBox1.Text = string.Empty;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
1st of all, your queries are quite weird, when you do INSERT, I dont see anywhere what do you actually insert (no data specified in your code), it should be like:
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text!=string.Empty)
{
//using means it will close and dispose the classes by it self! So no need to type Close() or Dispose() methods.
using (SqlConnection conn = new SqlConnection("ConnectionStringHere"))
{
bool bAllOK = false; //using and helping with some custom flag to get it all right
string query1 = #"INSERT INTO student_att (id, nic, name, address, number, batch) VALUES (#id, #nic, #name, #address, #number, #batch)";
string query2 = #"SELECT * FROM studetnt_att WHERE nibm_id LIKE #myText%";
//1. INSERT:
using (SqlCommand cmd = new SqlCommand(query1, conn))
{
cmd.Parameters.AddWithValue("#id", 1); //get new ID, best is to look for the last one in the DB, and increment by 1
cmd.Parameters.AddWithValue("#nic", "nickname1"); //get his nick name
//same way and and set all the other 4 parameters for name, address, number and batch here
try
{
connection.Open();
command.ExecuteNonQuery();
bAllOK = true;
}
catch(SqlException)
{
// error here if occures
}
}
if(bAllOK)
{
//2. SELECT:
using (SqlCommand cmd = new SqlCommand(query2, conn))
{
cmd.Parameters.AddWithValue("#myText", textBox1.Text);
DataTable table = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(table);
dataGridView2.DataSource = table;
}
}
}
}
}
else
MessageBox.Show("Please type some name...");
}
The 2nd query makes no sence, since you are looking for nibm_id is looking for IDS which starts with the number in textBox. Is that really what you are looking for? LIKE SOMETHING% means that it looks for SOMETHINGS which starts with that.

How to save an image database and display it on a panel on webpage?

I created a folder on a webform in visual studio for images and titled as (Invoices), I want to save the root of images in MySql database and display the images on a panel one the webpage. The image has been saved on the folder but not on database.
The Codes I have tried
protected void Page_Load(object sender, EventArgs e)
{
string connection = "server=localhost; userid= ; password= ; database=admindb; allowuservariables=True";
MySqlConnection cn = new MySqlConnection(connection);
try
{
string sqlcmd = "SELECT PicAddress FROM InvoicesFP WHERE InvoicesFP_ID=#InvoicesFP_ID";
cn.Open();
MySqlCommand cmd = new MySqlCommand(sqlcmd, cn);
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string url = rdr["PicAddress"].ToString();
Image1.ImageUrl = url;
}
}
catch (Exception ex)
{
throw ex;
}
cn.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
#region fileupload
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
string SaveLocation = Server.MapPath("Invoices\\") + Guid.NewGuid().ToString("N") + FileExtension;
MySqlConnection connection = new MySqlConnection("server=localhost; userid=root; password=admin1234; database=admindb; allowuservariables=True");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "insert into invoicesfp (PicAddress), VALUES (#PicAddress)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("PicAddress", Server.MapPath("~/Invoices"));
cmd.Connection.Open();
cmd.BeginExecuteNonQuery();
cmd.Connection.Close();
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
catch (Exception ex)
{
if (ex is ArgumentNullException || ex is NullReferenceException)
{
throw ex;
}
}
string PicAddress = "~/Invoices/" + SaveLocation;
}
#endregion
}
Update
Try this Code first, using this sample you do not need to use Rename Method And whatever its Extension is, it is supported:
#region fileupload
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
string SaveLocation = Server.MapPath("Invoices\\") + Guid.NewGuid().ToString("N") + "." + FileExtension;
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
catch (Exception ex)
{
if (ex is ArgumentNullException || ex is NullReferenceException)
{
throw ex;
}
}
string PicAddress = "~/Invoices/" + SaveLocation;
#endregion
MySqlConnection connection = new MySqlConnection("server=localhost; userid=root; password=admin1234; database=admindb; allowuservariables=True");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO InvoicesFP (PicAddress) VALUES (#PicAddress)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("PicAddress", "PicAddress");
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
then in your page_load you can call the Select Query to get the Address out database and pass it over to control e.g:
const string DB_CONN_STR = "Server=etc;Uid=etc;Pwd=etc;Database=etc;";
MySqlConnection cn = new MySqlConnection(DB_CONN_STR);
try {
string sqlCmd = "SELECT PicAddress FROM [YourTable] where Id == PicAddress id";
cn.Open(); // have to explicitly open connection (fetches from pool)
MySqlCommand cmd = new MySqlCommand(sqlCmd, cn);
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
string url = rdr["Name of the Field Assuming PicAddress"].ToString();
Image1.ImageUrl = url;
}
}
catch(Exception ex)
{
throw ex;
}
Thats All - Happy Coding

Selecting an option from dropdown menu to fill textboxes

I have filled the drop down menu with names from the my UserData database. I am currently trying to select an users name to make their user details appear in the textboxes, however when I try to select an option from the dropdown menu, the first option always appears in the textboxes I was wondering if anybody could see a problem in my code?
protected void BtnSelect_Click(object sender, EventArgs e)
{
SqlDataReader reader;
String connString = ConfigurationManager
.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm1 = new SqlCommand(
"SELECT FirstName, LastName, Email FROM UserData " +
"WHERE TeacherID = #TeacherID", conn);
comm1.Parameters.Add("#TeacherID", System.Data.SqlDbType.Int);
comm1.Parameters["#TeacherID"].Value = DropDownList1.SelectedItem.Value;
try
{
conn.Open();
reader = comm1.ExecuteReader();
if (reader.Read())
{
txtFirstName.Text = reader["FirstName"].ToString();
txtLastName.Text = reader["LastName"].ToString();
txtEmail.Text = reader["Email"].ToString();
}
reader.Close();
}
catch (Exception ex)
{
dbErrorLabel.Text = ("Error in retrieval"+ ex.StackTrace);
}
finally
{
conn.Close();
}
}
Try altering your code slightly like this and then you will find it easier to debug. Check what value you're getting for the selected value (is it what you expect) and also what the content of the actual exception is that you're getting.
This should help you to work out what's going on.
protected void BtnSelect_Click(object sender, EventArgs e)
{
SqlDataReader reader;
String connString = ConfigurationManager
.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm1 = new SqlCommand(
"SELECT FirstName, LastName, Email FROM UserData " +
"WHERE TeacherID = #TeacherID", conn);
var selectedValue = DropDownList1.SelectedItem.Value;
var selected = int.Parse(selectedValue);
comm1.Parameters.Add("#TeacherID", System.Data.SqlDbType.Int);
comm1.Parameters["#TeacherID"].Value = selected;
try
{
conn.Open();
reader = comm1.ExecuteReader();
if (reader.Read())
{
txtFirstName.Text = reader["FirstName"].ToString();
txtLastName.Text = reader["LastName"].ToString();
txtEmail.Text = reader["Email"].ToString();
}
reader.Close();
}
catch(Exception ex)
{
dbErrorLabel.Text = ("Error in retrieval " + ex.StackTrace );
}
finally
{
conn.Close();
}
}

Connect to two tables

I have created comboBox and filled with one column, after I choose item from the combobox I would like to show other column in the textboxs so I wrote code to make it happen but what if I want to choose column from another table I mean I would like to show couple of columns from two different table in the textbox when I hit the combobox
Here is my code:
private void comboLname_SelectedIndexChanged(object sender, EventArgs e)
{
string conn = "Data Source=srv-db-02;Initial Catalog=rmsmasterdbtest;Persist Security Info=True;User ID=test;Password=*******";
string Query = "select * from rmsmasterdbtest.dbo.customer where LastName= '" + comboLname.Text + "' ;";
SqlConnection Myconn = new SqlConnection(conn);
SqlCommand cmdDataBase = new SqlCommand(Query, Myconn);
SqlDataReader Reader;
try
{
Myconn.Open();
Reader = cmdDataBase.ExecuteReader();
while (Reader.Read())
{
string ID = Reader.GetInt32(Reader.GetOrdinal("ID")).ToString();
string AccountNuber = Reader.GetString(Reader.GetOrdinal("AccountNumber"));
//string Time = Reader.GetString(Reader.GetOrdinal("Time"));
// string Deposit = Reader.GetString(Reader.GetOrdinal("Deposit"));
string sstatus = Reader.GetString(Reader.GetOrdinal("status"));
string slastname = Reader.GetString(Reader.GetOrdinal("lastname"));
txtid.Text = ID;
txtacnum.Text = AccountNuber;
//txttime.Text = Time;
//txtdeposit.Text = Deposit;
txtstatus.Text = sstatus;
txtlname.Text = slastname;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
Myconn.Close();
}
}

check existing record before inserting sql database

I created a simple asp.net form which allow users to view a list of dates for a training and register for that date , they enter their name and employeeid manually ( i dont want to allow dulpicate employe ids), so I need to figure out how to check this on c#..
code:
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
private void checkContraint()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select "; //NEED HELP HERE
}
private void InsertInfo()
{
var dateSelected = dpDate.SelectedItem.Value;
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT #Val1b+','+#Val1,#Val2,#Val3,#Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id =#training_id ";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Val1", txtName.Text);
cmd.Parameters.AddWithValue("#Val1b", txtLname.Text);
cmd.Parameters.AddWithValue("#Val2", txtDept.Text);
cmd.Parameters.AddWithValue("#Val3", txtTitle.Text);
cmd.Parameters.AddWithValue("#Val4", txtEmployeeID.Text);
//Parameter to pass for the select statement
cmd.Parameters.AddWithValue("#training_id", dateSelected);
cmd.CommandType = CommandType.Text;
//cmd.ExecuteNonQuery();
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 1)
{
//Success notification // Sends user to redirect page
Response.Redirect(Button1.CommandArgument.ToString());
ClearForm();
}
else
{
//Error notification
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
checkContraint();
InsertInfo();
this way , your query will insert data only if not exists already
string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT #Val1b+','+#Val1,#Val2,#Val3,#Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id =#training_id and not exists (select 1 from personTraining pp where pp .employeeid=#Val4) ";

Categories