Textbox data is not adding to the database - c#

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.

Related

Receive/Load user data after login C# WPF

After successful login to application i want to get other data from sql of that user like: name, surname, birthdate etc. and put it into dashboard.sellerinfo.Text;
private void button_Click(object sender, RoutedEventArgs e)
{
DBconnection con1 = new DBconnection();
try
{
con1.connection();
String query = "SELECT * FROM Seller WHERE Login=#Login and Password=#Password";
SqlCommand Sqlcmd = new SqlCommand(query, con1.con);
Sqlcmd.CommandType = System.Data.CommandType.Text;
Sqlcmd.Parameters.AddWithValue("#Login", login.Text);
Sqlcmd.Parameters.AddWithValue("#Password", password.Password);
int count = Convert.ToInt32(Sqlcmd.ExecuteScalar());
if(count==1)
{
MainWindow dashboard = new MainWindow();
dashboard.Show();
this.Hide();
}
else
{
MessageBox.Show("Username or password is incorrect.");
password.Clear();
login.Clear();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con1.close();
}
}
I tried a lot with reader but something went wrong. Do you have any advice? Thanks
Don't use ExecuteScalar() when you intend to select data from the table. You could for example load the entire result set into a DataTable using the ExecuteReader() method:
String query = "SELECT * FROM Seller WHERE Login=#Login and Password=#Password";
SqlCommand Sqlcmd = new SqlCommand(query, con1.con);
Sqlcmd.CommandType = System.Data.CommandType.Text;
Sqlcmd.Parameters.AddWithValue("#Login", login.Text);
Sqlcmd.Parameters.AddWithValue("#Password", password.Password);
DataTable dt = new DataTable();
dt.Load(Sqlcmd.ExecuteReader());
if (dt.Rows.Count == 1)
{
string name = dt.Rows[0]["Name"].ToString();
//...
MainWindow dashboard = new MainWindow();
dashboard.Show();
this.Hide();
}
...
You can then access any column of the first row of the populated DataTable like this where "Name" corresponds to a column named "Name" in the "Seller" table:
dt.Rows[0]["Name"]

Update DB with updated Textbox Information in 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

How to show Data in table?

I am a beginner in C# and using MS Visual Studio 2010. Ans my problem is I am inserting data through textbox in a table named as (tbl_employees) and saving it successfully.
After saving when I see the table the new inserted data is not showing in tbl_employee even after updating.
Here is my code for updating table
private void btnupdate_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlDataAdapter da;
string sql = "SELECT * From tbl_employees";
da = new System.Data.SqlClient.SqlDataAdapter(sql , conString);
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
DataRow row = ds.Tables[0].Rows[inc];
dRow[1] = textBox1.Text;
dRow[2] = textBox2.Text;
MaxRows = MaxRows + 1; //to enable last row is still last row
inc = MaxRows - 1;
MessageBox.Show("Now Table is updated too. . . ");
}
Code with ease to understand and implement
Insert
private void Insert()
{
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Insert into YourTable Select (#Val1,#Val2,#Val3)";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
command.Parameters.Add("#Val1",txt1.Text);
command.Parameters.Add("#Val2",txt2.Text);
command.Parameters.Add("#Val3",txt3.Text);
int i = command.ExecuteNonQuery();
con.Close();
}
}
}
Update
private void Update()
{
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Update YourTable Set Field1=#Val1,Field2=#Val2,Field3=#Val3 Where YourPrimaryKey=#Key";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
command.Parameters.Add("#Val1",txt1.Text);
command.Parameters.Add("#Val2",txt2.Text);
command.Parameters.Add("#Val3",txt3.Text);
command.Parameters.Add("#Key",txt4.Text);
int i = command.ExecuteNonQuery();
con.Close();
}
}
}
Select
private DataTable Get()
{
DataTable dt = new DataTable();
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Select * From YourTable";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
using(var reader = command.ExecuteReader(CommandBehaviour.CloseConnection))
{
dt.Load(reader);
}
con.Close();
}
}
return dt;
}
So now you have a Get method that returns DataTable , now you need a grid to display that data. Quite simple.
ASP.Net
private void BindGrid()
{
gridview1.DataSource = Get();
gridView1.DataBind();
}
Winforms
Same as above except we need not call DataBind().

Fetching and displaying tables on database

I'm just starting out at asp.net c# and I have been given a task to generate the available doctors upon the given values in a drop-down list.
I have 3 drop-down lists, (1)PROVINCE, (2)CITY, (3)SPECIALIZATION and a search button.
After the user selects the values of 3 drop-down lists and hits the search button it will print a table containing the available doctor.
I know that the key is on the search button, but I don't exactly know what to put under the search button. Can you help me out please?
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
if (!IsPostBack)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_city");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("select distinct emed_accredited_providers.SPECIALIZATION from emed_accredited_providers inner join emed_doctors_hospitals on emed_accredited_providers.DOCTOR_CODE = emed_doctors_hospitals.DOCTOR_CODE where CITY_CODE =#ccode", conn);
comm.Parameters.AddWithValue("#ccode", ddlCity.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#ccode";
param.Value = ddlCity;
comm.Parameters.Add(param);
}
ddlSpec.DataSource = dt;
ddlSpec.DataTextField = "SPECIALIZATION";
ddlSpec.DataValueField = "SPECIALIZATION";
ddlSpec.DataBind();
}
protected void btnDocs_Click(object sender, EventArgs e)
{
}
}
}
string query = string.Empty;
if (ddlProvince.SelectedIndex != -1)
{
query = query + " and PROVINCE_CODE=" + ddlProvince.SelectedValue;
}
if (ddlCity.SelectedIndex != -1)
{
query = query + " and CITY_CODE=" + ddlProvince.SelectedValue;
}
if (ddlSpec.SelectedIndex != -1)
{
query = query + " and SPECIALIZATION=" + ddlProvince.SelectedValue;
}
string tQuery = "Select * from Doc";
if (query.Length > 0)
{
query = query.Remove(0, 4);
tQuery = tQuery + query;
}
// Exeucate -- tQuery
// Modify table name or field name.
get the selected values from the drop down list
pass the selected values to your search function. (It depends on your logic, I mean if user select values from only one drop down, from only two drop down your search query may differ).
get the return values from your search function and bind it to your table (grid view)
Also have a look at the DropDownList.SelectedIndex Property
to bind the gridview you can do something similar to this
private void BindGrid ()
{
var dt = new DataTable();
var connection = new SqlConnection(YOUR CONNECTION);
try
{
connection.Open();
var query = "YOUR SEARCH QUERY";
var sqlCmd = new SqlCommand(query, connection);
var sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
//
}
finally
{
connection.Close();
}
}

Checking condition which table to Insert

I want to Check the "refno" already present in Tbldelivery table, If "refno" is present, then it will insert in "Tbldeliverydetails" because "refno" is primary key in 1st table. Where i check the condition ?
Here is the code i wrote in C# :
protected void btndlysave_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection("server=(local);Initial Catalog=TestDB;Integrated Security=SSPI;");
try
{
SqlCon.Open();
SqlCommand cmd = new SqlCommand("insert into Tbldelivery (refno,deliverdate,requestby,projectcode) values
(#refno,#deliverdate,#requestby,#projectcode) WHERE not exists (select refno from Tblinkdelivery where refno = #refno)", SqlCon);
cmd.CommandType = CommandType.Text;
if ( need check here)
cmd.Parameters.AddWithValue("#refno", txtdelrefno.Text.Trim());
cmd.Parameters.AddWithValue("#deliverdate", txtdeldate.Text.Trim());
cmd.Parameters.AddWithValue("#requestby", txtdelreq.Text.Trim());
cmd.Parameters.AddWithValue("#projectcode", ddlprojcode.Text.Trim());
}
else
{
SqlCommand cmd2 = new SqlCommand("insert into Tbldeliverdetails (refno,printercode,inkcode,quantity,price,notes) values (#refno,#printercode,#inkcode,#quantity,#price,#notes)", SqlCon);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.AddWithValue("#refno", txtdelrefno.Text.Trim());
cmd2.Parameters.AddWithValue("#printercode", ddldelprcode.Text.Trim());
cmd2.Parameters.AddWithValue("#inkcode", ddlinkcode.Text.Trim());
cmd2.Parameters.AddWithValue("#quantity", txtdelqty.Text.Trim());
cmd2.Parameters.AddWithValue("#price", txtdelprice.Text.Trim());
cmd2.Parameters.AddWithValue("#notes", txtdelnotes.Text.Trim());
int val1 = cmd.ExecuteNonQuery();
int val2 = cmd2.ExecuteNonQuery();
}
finally
{
SqlCon.Close();
}
}
I think first of all you need to arrange your code.
Writing everything inside the button click event is not good at all. It is better if you can separate business logic and put it separately.
Try something like this.
You can create Data Access class which handle your data access.
In your Data Access Class
public SqlConnection OpenConnection()
{
try
{
var conn = new SqlConnection(“xxx”);
conn.Open();
return conn;
}
catch (Exception ex)
{
//log the exception
return null;
}
}
YourFunction(parameters)
{
var conn = OpenConnection();
if(conn != null)
{
//your code
// you can do something similar as JeremyK explained here
}
}
And in your button click
protected void btndlysave_Click(object sender, EventArgs e)
{
//CHECK THE PARAMETERS AND PASS
//DataAccess. YourFunction(parameters)
}
You query the table and see if it exists.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand sqlCommand =
new SqlCommand("SELECT * FROM dbo.Tbldelivery WHERE refno=#refno",
connection);
sqlCommand.Parameters.Add("#refno", System.Data.SqlDbType.VarChar);
sqlCommand.Parameters["#refno"].Value = refnoValue;
SqlDataReader reader = sqlCommand.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
// refno exists
}
else
{
// refno does not exist
}
}

Categories