I have two tables in the database one is UserAuth and the other is CarAdd, but I need to show UserName from the UserAuth table in my CarAdd dataGridView1 section.
This method shows all data from my CarAdd table:
void Bindata()
{
SqlCommand cmd = new SqlCommand("select * from CarAdd", con);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
dataGridView1.ItemsSource = dt.DefaultView;
}
But, now I need to show the username from the UserAuth table in the dataGridView1 section.
I have tried this code:
void BindataUserName()
{
SqlCommand cmd = new SqlCommand("select * from UsreAuth where UserName='UserName'", con);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
// dataGridView1.ItemsSource = dt.DefaultView;
}
Here is my save click button, actually I need to save and show username on dataGridView1 after click this button:
private void save_Click(object sender, RoutedEventArgs e)
{
if (carid.Text != "" && cartype.Text != "" && model.Text != "" && intime.Text!="" && outtime.Text!="" && slotgroup.Text!="")
{
try
{
con.Open();
string newcon = "insert into CarAdd (carid, cartype, carmodel, duration, payment, slot_book, insertdate) values ('" + carid.Text + "','" + cartype.Text + "','" + model.Text + "', '" +txtduration.Text+ "','" +txtpayment.Text+ "','"+ slotgroup.Text +"' ,getdate())";
SqlCommand cmd = new SqlCommand(newcon, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully inserted");
Bindata();
// TimeShow();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
else
{
MessageBox.Show("Invalid credentials");
}
}
Note: I have created a WPF Windows application for this project
Thank you!
Since UserName is an attribute in the UserAuth table, the SQL query must be modified accordingly to fetch it.
SELECT UserName
FROM UserAuth
So for the Bindatausername() method, the SqlCommand should be changed to the following:
void BindataUserName()
{
SqlCommand cmd = new SqlCommand("select UserName from UserAuth where UserName='UserName'", con);
Related
Hi I'm creating a C# program where users can login and book bus seats for destinations, I have the program so users can insert/update/delete data but I want the data to just display the currently logged-in data, this is my code below.
This function is in the main dashboard class where it displays the seats table to the dataviewgrid
private void displayBookings()
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
This is my database table and all I want to do once a user is logged in is display each seatID by the userID, the seatid is the primary key for this table and the userid is a foreign key linked to the userdata table.
EDIT:
private void displayBookings()
{
SqlConnection con = new SqlConnection(#"CONNECTIONSTRING");
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats WHERE userID = #userID";
//add the user id as a parameter
SqlParameter p_userID = new SqlParameter("#userID", SqlDbType.Int);
// the userID of the logged in user
p_userID.Value = cmd.Parameters.Add(p_userID);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Login method
private void loginButton_Click(object sender, EventArgs e)
{
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Brandon Brock\source\repos\SE2\Booking System\Database1.mdf;Integrated Security=True"))
{
con.Open();
string str1 = "select * from userdata where username='" + log_username.Text + "' and password_1='" + log_password.Text + "'";
SqlCommand cmd = new SqlCommand(str1, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(str1, con);
da.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 1)
{
switch (dt.Rows[0]["type"] as string)
{
case "admin":
{
MessageBox.Show("You are logged in!", "Admin Portal", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
new Admin().Show();
break;
}
case "user":
{
MessageBox.Show("You are logged in!", "Seat Reservation", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
new Dashboard().Show();
break;
}
default:
{
MessageBox.Show("Enter Correct Username and Password");
break;
}
}
log_username.Text = "";
log_password.Text = "";
}
else
{
MessageBox.Show("Username or Password is wrong or Account doesn't exist!", "Bus Seat Account Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (SqlException ex)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Console.WriteLine(errorMessages.ToString());
}
}
}
Assuming you have access to the logged in user data:
con.Open(); // <-- can't see where this comes from but is almost certainly an anti-pattern. Don't re-use SqlConnection instances, make new ones and Dispose() when done.
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats WHERE userID = #userID";
//add the user id as a parameter
SqlParameter p_userID = new SqlParameter("#userID", SqlDbType.Int);
p_userID.Value = // the userID of the logged in user
cmd.Parameters.Add(p_userID);
//cmd.ExecuteNonQuery(); <-- this is pointless, delete it
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
I can't find my problem. Can anyone help me to check it. I'm new in C#.
public void Btnchange_Click(object sender, EventArgs args)
MySqlConnection con = new MySqlConnection("server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234");
MySqlDataAdapter sda = new MySqlDataAdapter("select Password from user.register where Password='" + textoldpassword.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count.ToString() == "1")
{
if (textnewpassword.Text == textconfirmpassword.Text)
{
con.Open();
MySqlCommand cmd = new MySqlCommand("update user.register set Password ='" + textconfirmpassword.Text + "' where Password ='" + textoldpassword.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
lblmsg.Text = "Succesfully Updated";
lblmsg.ForeColor = Color.Green;
}
else
{
lblmsg.Text = "New password and confirm password should be same!";
}
I expect it can update and change my password.
There are many many (mostly) minor mistakes in your code:
use some kind of Id fields in your sql tables
never do an update like you did (update the field WHERE this field is equals to...)
create your own class and bind the query result to this class
when a class implements IDisposable interface, always use the keyword 'using'
never ever user string concatenation in sql queries!!! SQL INJECTION!!! always use parametrized sql queries
Here's a simple example for your form. Let's suppose your
user.register table has the following columns:
- Id
- Username
- Password
Now let's create your own class (maybe right under your button click
event, so it can be private this time):
private class MyUser
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
Then your button click event should look like this:
private void Btnchange_Click(object sender, EventArgs e) {
if (!textnewpassword.Text.Trim().Equals(textconfirmpassword.Text.Trim()))
{
throw new ArgumentException("New password and confirm password should be same!");
}
List<MyUser> myUsers = new List<MyUser>();
using (MySqlConnection con =
new MySqlConnection(
"server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234"))
{
using (MySqlCommand cmd = new MySqlCommand("select * from user.register where Username=#user and Password=#pass", con))
{
cmd.Parameters.AddWithValue("#user", textusername.Text.Trim());
cmd.Parameters.AddWithValue("#pass", textoldpassword.Text.Trim());
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
using (MySqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
myUsers.Add(new MyUser
{
Id = (int)dr["Id"],
Username = dr["Username"].ToString(),
Password = dr["Password"].ToString()
});
}
}
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
if (!myUsers.Any())
{
throw new ArgumentException("No users found with the given username/password pair!");
}
if (myUsers.Count != 1)
{
throw new ArgumentException("More than 1 user has the same username and password in the database!");
}
MyUser user = myUsers.First();
user.Password = textnewpassword.Text.Trim();
using (MySqlCommand cmd = new MySqlCommand("update user.register set Password=#pass where Id=#id"))
{
cmd.Parameters.AddWithValue("#pass", user.Password);
cmd.Parameters.AddWithValue("#id", user.Id);
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
cmd.ExecuteNonQuery();
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
} }
...and so on.
friends
please if you have time to solve my problem
i have many textbox in my form with one button and one datagridview
i use this code to make the search
What if i want to perform a search using values from 2 or more text boxes. what if I typed in "r" in the Name text box then also typed "NY" in the city text box. I want to see the gridview give me the results of that.
that what i try to find and i didn't find anything
the code is working if i search in one textbox only
warm regards
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (txtCIVILIDD.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where CIVILIDD = '" + txtCIVILIDD.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (txtName_Arabic.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Name_Arabic like '%" + txtName_Arabic.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (txtusername.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where username = '" + txtusername.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBox1.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where status = '" + comboBox1.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBox2.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where confirmation = '" + comboBox2.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (CBgender.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where gender like '%" + CBgender.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (CBNATIONALITY.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where NATIONALITY like '" + CBNATIONALITY.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBoxGovernorate.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Governorate = '" + comboBoxGovernorate.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBoxCity.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where City = '" + comboBoxCity.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
dataGridView1.DataSource = dt;
i try to solve my problem with this code bout i find "SELECT * FROM tabl1 WHERE 1=1 ";
it return null to me
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
StringBuilder sqlcommand = "SELECT * FROM tabl1 WHERE 1=1 ";
if (!string.IsNullOrEmpty(CBgender.Text))
{
sqlcommand.Append(" and GENDER LIKE '%");
sqlcommand.Append(CBgender.Text);
sqlcommand.Append("%'");
}
// repeat for other textbox fields
dataGridView1.DataSource = dt;
}
my search form
Here are two possible approaches. The first uses #WelcomeOverflows's suggestion which is to use the RowFilter property of the DataTable. The advantage of doing so is that you only have to perform one database query and the filtering is handled client side. However, it isn't possible to protect RowFilter from SQL injection easily (but while you can still potentially subvert the filtering intention, the damage you can do on a disconnected data source is limited). Also if the dataset is enormous, it might not be desirable to pull back the entire dataset at once and keep it in memory.
// call upon startup to get all the data one time
private void GetData()
{
DataTable dataSource = new DataTable();
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString))
{
connection.Open();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM tabl1", connection);
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
adapter.Fill(dataSource);
dataGridView1.DataSource = dataSource;
}
}
// create a filter for the given field in the database and our control
private string CreateFilter(string fieldName, Control userInputControl, bool exactMatch)
{
string searchValue = null;
if (userInputControl is TextBox) searchValue = ((TextBox)userInputControl).Text;
if (userInputControl is ComboBox) searchValue = ((ComboBox)userInputControl).Text;
if (String.IsNullOrWhiteSpace(searchValue)) return null;
if (exactMatch)
return String.Format("{0}='{1}'", fieldName, searchValue);
return String.Format("{0} LIKE '%{1}%'", fieldName, searchValue);
}
// set the filter on our data grid view
private void button1_Click(object sender, EventArgs e)
{
var filterConditions = new[] {
CreateFilter("Name_Arabic", txtName_Arabic, false),
CreateFilter("gender", CBgender, false),
CreateFilter("CIVILIDD", txtCIVILIDD, true),
CreateFilter("NATIONALITY", cbNationality, false)
// etc.
};
var dataSource = (DataTable)dataGridView1.DataSource;
if (!filterConditions.Any(a => a != null))
{
dataSource.DefaultView.RowFilter = null;
return;
}
dataSource.DefaultView.RowFilter = filterConditions
.Where(a => a != null)
.Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2));
}
Second approach is to filter directly in the database query, using SQL parameters to avoid SQL injection.
private string CreateSqlFilter(string fieldName, Control userInputControl, SqlCommand command, bool exactMatch)
{
string searchValue = null;
if (userInputControl is TextBox) searchValue = ((TextBox)userInputControl).Text;
if (userInputControl is ComboBox) searchValue = ((ComboBox)userInputControl).Text;
if (String.IsNullOrWhiteSpace(searchValue)) return null;
if (exactMatch)
{
command.Parameters.Add(new SqlParameter("#" + fieldName, searchValue));
return fieldName + " = #" + fieldName;
}
else
{
command.Parameters.Add(new SqlParameter("#" + fieldName, "%" + searchValue + "%"));
return fieldName + " LIKE #" + fieldName;
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlCommand selectCommand = new SqlCommand();
var filterConditions = new[] {
CreateSqlFilter("Name_Arabic", txtName_Arabic, selectCommand, false),
CreateSqlFilter("gender", CBgender, selectCommand, false),
CreateSqlFilter("CIVILIDD", txtCIVILIDD, selectCommand, true),
CreateSqlFilter("NATIONALITY", cbNationality, selectCommand, false)
// etc.
};
string filterCondition = filterConditions.Any(a => a != null) ? filterConditions.Where(a => a != null).Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2)) : (string)null;
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString))
{
selectCommand.Connection = connection;
selectCommand.CommandText = filterCondition == null ? "SELECT * FROM tabl1" : "SELECT * FROM tabl1 WHERE " + filterCondition;
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
DataTable dataSource = new DataTable();
adapter.Fill(dataSource);
dataGridView1.DataSource = dataSource;
}
}
Create StringBuilder object:
StringBuilder sqlcommand = new StringBuilder("SELECT * FROM tabl1 WHERE 1=1");
You can create a parametrized query which considers parameters having null values as neutral in search. For example:
SELECT * FROM Product WHERE
(Id = #Id OR Id IS NULL) AND
(Name LIKE '%' + #Name + '%' OR #Name IS NULL) AND
(Price = #Price OR #Price IS NULL)
This way, if you pass NULL for any of the parameters, that parameter will not be considered in search.
Also as a side note, it prevents SQL Injection, by using parameters.
Example
The following example assumes you have a table called Product, having a column named Id as INT, Name as NVARCHAR(100) and Price as INT.
Then to load data, create the following method:
public DataTable GetData(int? id, string name, int? price)
{
DataTable dt = new DataTable();
var commandText = "SELECT * FROM Products WHERE " +
"(Id = #Id OR #Id is NULL) AND " +
"(Name LIKE '%' + #Name + '%' OR #Name IS NULL) AND " +
"(Price = #Price OR #Price IS NULL)";
var connectionString = #"Data Source=.;Initial Catalog=SampleDb;Integrated Security=True";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#Id", SqlDbType.Int).Value =
(object)id ?? DBNull.Value;
command.Parameters.Add("#Name", SqlDbType.NVarChar, 100).Value =
(object)name ?? DBNull.Value;
command.Parameters.Add("#Price", SqlDbType.Int).Value =
(object)price ?? DBNull.Value;
using (var datAdapter = new SqlDataAdapter(command))
datAdapter.Fill(dt);
}
return dt;
}
To get values from TextBox controls and pass to GetData, you can use the following code:
var id = int.TryParse(idTextBox.Text, out var tempId) ? tempId : default(int?);
var name = string.IsNullOrEmpty(nameTextBox.Text)?null:nameTextBox.Text;
var price = int.TryParse(priceTextBox.Text, out var priceId) ? priceId : default(int?);
Then to get data:
var data = GetData(id, name, price);
SqlConnection con = new SqlConnection(#"Data Source=STRONGLION;Initial Catalog=GIP;Integrated Security=True");
private void btnLogin_Click(object sender, EventArgs e)
{
SqlDataAdapter sda = new SqlDataAdapter("Select count(*) from tblLogin where Gebruikersnaam = '" + txtGebruikersnaam.Text + "' and Paswoord = '" + txtPaswoord.Text + "' and Accounttype'" + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (Accounttype == "1")
{
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
FormAdmin ss = new FormAdmin();
ss.Show();
}
else
{
MessageBox.Show("Error");
}
}
else if (Accounttype == "0")
{
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
FormWerknemer ss = new FormWerknemer();
ss.Show();
}
else
{
MessageBox.Show("Error");
}
}
}
I have a login form that reads data from a database. What I want is that I can open a form based on what type of user logs in. Above you see a general example how I want it to work.
For example in the database I have 3 things username, password and accounttype, if account type is 1 then its an admin type of account if its 0 then its just a normal account.
Hope someone can help out, thanks in advance!
Your query is wrong, the last part of your WHERE statement is meaningless
"' and Accounttype'" + "'", con);
where is the value for the field Accounttype?
However there is a bigger problem here and is the string concatenation to build your sql text. This could be used to create an Sql Injection attack or it could be simply a source of bugs if your input values cannot be correctly parsed.
You could use a parameterized query as this one
string cmdText = #"Select count(*)
from tblLogin
where Gebruikersnaam = #name and
Paswoord = #pwd and
Accounttype = #type";
and there is no need to build an SqlDataAdapter and a DataTable if you want to get a simple scalar value from your data (the count)
using(SqlConnection con = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = txtGebruikersnaam.Text;
cmd.Parameters.Add("#pwd", SqlDbType.NVarChar).Value = txtPaswoord.Text;
cmd.Parameters.Add("#type", SqlDbType.NVarChar).Value = Accounttype;
int countType = Convert.ToInt32(cmd.ExecuteScalar());
if(countType == 0)
MessageBox.Show("No user found for the type requested");
else
{
if (Accounttype == "1")
{
this.Hide();
FormAdmin ss = new FormAdmin();
ss.Show();
}
else if (Accounttype == "0")
{
this.Hide();
FormWerknemer ss = new FormWerknemer();
ss.Show();
}
}
}
Consider also the advice given in the comments above. You should not store passwords in plain text inside the database. This is a big security risk because everyone that could look at your table could see the password of your users.
This is my code and error message when you running say:
An unhandled exception of type System.Data.SqlClient.SqlException
occurred in System.Data.dll
on this da.fill(dt);
SqlConnection con = new SqlConnection("Data Source=ANTONIANGGA-PC\\SQLEXPRESS;Initial Catalog=FullandStarving;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
public FormProduksi()
{
InitializeComponent();
showgridview();
}
private void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure; done :D
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
showgridview();
clear();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
that update successfully but cant refresh, so i do quit that form and open can see it
You are closing the connection
con.Close();
and then using
da.Fill(dt);
Just swap this lines:
showgridview();
con.Close();
For example with DbDataAdapter.Fill:
Notes:
1
Yoy should use parametrized queries so you avoid SQL Injection attacks:
var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con);
cmd.Parameters.AddWithValue("#id", id.Text);
2
Wrap SqlConnection and SqlCommand into using so any resources used by those would disposed:
string position;
using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
con.Open();
using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con))
{
cmd.Parameters.AddWithValue("#id", id.Text);
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
}
}
Credit
Just change the showgridview() function as below where connection is opened & closed properly.
Also check your sql query ,provide space and maintain syntax of query :
SELECT * FROM Produksi
Error screenshot clearly depicts that stored procedure with such name don't exist
comment out those lines as code below :
void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Then you wont be having connection issues and errors related .
Button Click code change the closing connection as below:
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try
{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
con.Close();
showgridview();
clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Also, for further reading:
parameterized queries vs. SQL injection
Why do we always prefer using parameters in SQL statements?