I am using winform C#,
database name "School"
my "fees" table has 2 columns,
stu_id,fees
The issue I am facing is that it adds multiple (same) entries into the database instead of single.
I have code on other forms but I don't know why is this happening here, any help would be appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SchoolManagementSystem
{
public partial class Fees : Form
{
public Fees()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DRAGON\SQLEXPRESS;Initial Catalog=School;Integrated Security=True;");
con.Open();
try
{
string str = " INSERT INTO fees VALUES('" + textBox1.Text + "','" + textBox2.Text + "')";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Your Fees Submitted..");
this.Hide();
Home obj2 = new Home();
obj2.ShowDialog();
}
this.Close();
}
catch (SqlException excep)
{
MessageBox.Show(excep.Message);
}
con.Close();
}
private void textBox1_MouseLeave(object sender, EventArgs e)
{
textBox2.Text = "";
SqlConnection con = new SqlConnection(#"Data Source=DRAGON\SQLEXPRESS;Initial Catalog=School;Integrated Security=True;");
con.Open();
if (textBox1.Text != "")
{
try
{
string getCust = "select name,standard,medium from student where std_id=" + Convert.ToInt32(textBox1.Text) + " ;"; // saving new custmer info
SqlCommand cmd = new SqlCommand(getCust, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.Read())
{
label9.Text = dr.GetValue(0).ToString();
label6.Text = dr.GetValue(1).ToString();
label7.Text = dr.GetValue(2).ToString();
}
else
{
MessageBox.Show("Sorry '" + textBox1.Text + "' This Registration Id is Invalid, Please Insert Correct Id");
textBox1.Text = "";
textBox2.Text = "";
}
}
catch (SqlException excep)
{
MessageBox.Show(excep.Message);
}
con.Close();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void Fees_Load(object sender, EventArgs e)
{
}
}
}
when I enter fees from front end, it adds same 2 rows into database instead of 1.
Because you're executing your INSERT statement twice:
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
Why? Why do you even need the SqlDataReader? Just execute the INSERT once:
cmd.ExecuteNonQuery();
MessageBox.Show("Your Fees Submitted..");
If you want to confirm that a row was inserted, ExecuteNonQuery returns the number of rows affected:
var rows = cmd.ExecuteNonQuery();
if (rows != 1)
{
// handle error
}
else
{
MessageBox.Show("Your Fees Submitted..");
}
You are executing the command twice here:
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
Why are you calling ExecuteReader when there's nothing to read? ExecuteReader is for when you execute a SELECT statement with multiple columns and/or multiple rows and you want to read the result set. For an INSERT statement, you only need to call ExecuteNonQuery... because it's not a query.
Related
Hello I'm practicing on typing codes of inventory system of products for the pos software.
I'm working on something like here:
Click here to see my products of inventory sketch.
And after a click on the save button for the results of the database then it should show up like the "record added...." window. And I don't see the result even I don't see any error on my visual studio pro software.
And please let me know which part is wrong and how to fix that.
Here is my code of salesn.cs file
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace superpos3
{
public partial class salesn : Form
{
public salesn()
{
InitializeComponent();
}
int totalPrice = 0;
MySqlConnection con = new MySqlConnection("server= localhost; database =superpos; username= root; password=; ");
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void txtno_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
txtqty.Enabled = true;
txtqty.Focus();
}
}
private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
try
{
string txt = "select * from products where id='" + txtno.Text + "'";
MySqlCommand cmd = new MySqlCommand(txt, con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
int price = int.Parse(txtqty.Text.ToString()) * int.Parse(r[4].ToString());
totalPrice = totalPrice + price;
//discount
// totalPrice = totalPrice - totalPrice* Payment.discount/100;
dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);
}
lbitems.Text = " " + (dataGridView1.RowCount - 1) + "";
lbtotal.Text = " " + totalPrice + " ";
con.Close();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message, "Error From Database");
}
txtno.Focus();
txtno.Clear();
txtqty.Enabled = false;
txtqty.Clear();
}
}
private void txtqty_TextChanged(object sender, EventArgs e)
{
}
private void salesn_Load(object sender, EventArgs e)
{
lbldate.Text = DateTime.Today.ToString("dd/MM/yyyy");
lbltime.Text = DateTime.Now.ToShortTimeString();
con.Open();
string query = "select max(id) from salesmain ";
MySqlCommand cmd2 = new MySqlCommand(query, con);
MySqlDataReader dr;
dr = cmd2.ExecuteReader();
if (dr.Read())
{
string val = dr[0].ToString();
if (val == "")
{
lbinvoice.Text = "1";
}
else
{
int a;
a = int.Parse(dr[0].ToString());
a = a + 1;
lbinvoice.Text = a.ToString();
}
con.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,price,grosstotal)values(#salesid,#productname,#qty,#price,#grosstotal)";
cmd.Parameters.AddWithValue("#saleid", lbinvoice.Text);
cmd.Parameters.AddWithValue("#productname", dataGridView1.Rows[i].Cells[2].Value);
cmd.Parameters.AddWithValue("#qty", dataGridView1.Rows[i].Cells[3].Value);
cmd.Parameters.AddWithValue("#price", dataGridView1.Rows[i].Cells[4].Value);
cmd.Parameters.AddWithValue("#grosstotal", dataGridView1.Rows[i].Cells[5].Value);
MySqlCommand cmd1 = new MySqlCommand();
cmd1.Connection = con;
cmd1.CommandText = "insert into salesmain(id,date,time,qty,grosstotal)values(#id,#date,#time,#qty,#grosstotal)";
cmd1.Parameters.AddWithValue("#id", lbinvoice.Text);
cmd1.Parameters.AddWithValue("#date", lbldate.Text);
cmd1.Parameters.AddWithValue("#time", lbltime.Text);
cmd1.Parameters.AddWithValue("#qty", lbitems.Text);
cmd1.Parameters.AddWithValue("#grosstotal", lbtotal.Text);
con.Open();
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
MessageBox.Show("Record added ..........");
con.Close();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
I guess you should check if the dataGridView1.Rows.Count is not zero because if it is, the for loop won't even run which means that neither your code nor the message box show method is gonna run.
the other MessageBox.Show() methods are inside catch blocks which obviously means that they won't run if the catch block doesn't catch any errors.
I wrote a code for my pleasure.
i have access data file "mdb" and i show him on gridview from gridview i select row and shown on text box.
i edit the textbox and try to press on Save button and show me error msg.
what i do wrong?
save button didnt save and show me error msg.
add pictures and my code:
Error msg
gridview+textbox
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Center image description hereDHW
{
public partial class Form2 : Form
{
private OleDbConnection connection = new OleDbConnection();
public Form2()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\RBA\Desktop\123\users1.mdb;
Persist Security Info=False;";
}
private void button9_Click(object sender, EventArgs e)
{
this.Close();
Form1 f1 = new Form1();
f1.Show();
}
private void btn_save_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into GRL1 (NoBoard,Site,Group,Kind,Unit) values ('" + txt_noboard.Text + "','" + txt_site.Text + "','" + txt_group.Text + "','" + txt_kind.Text + "','" + txt_unit.Text + "',)";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'users1DataSet.GRL1' table. You can move, or remove it, as needed.
this.gRL1TableAdapter.Fill(this.users1DataSet.GRL1);
}
private void btn_loadGR_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from GRL1";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from GRS1";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
txt_noboard.Text = row.Cells[0].Value.ToString();
txt_site.Text = row.Cells[1].Value.ToString();
txt_group.Text = row.Cells[2].Value.ToString();
txt_kind.Text = row.Cells[3].Value.ToString();
txt_unit.Text = row.Cells[4].Value.ToString();
txt_com.Text = row.Cells[5].Value.ToString();
}
}
}
}
You have a typo in your sql text. There is a comma before the close brace. But there is also an error caused by the usage of a reserved keyword in MS-Access (Group). You need to put square brackets around that name.
Finally, do not use string concatenation to build sql commands but always use parameters.
This avoid sql injection hacks and remove problem with parsing your inputs (for example if there is a single quote in your input text the whole query will fail again with a syntax error)
private void btn_save_Click(object sender, EventArgs e)
{
try
{
using(OleDbConnection connection = new OleDbConnection(....con string...))
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
// Notice how Group field is between square brackets.
// If you can I suggest to change the name of this field
string cmdText = #"insert into GRL1 (NoBoard,Site,[Group],Kind,Unit)
values (#nob, #sit, #grp, #knd, #uni)";
command.CommandText = cmdText;
// Is NoBoard an integer? If yes you should pass an integer not a string
command.Parameters.Add("#nob", OleDbType.Integer).Value = Convert.ToInt32(txt_noboard.Text);
command.Parameters.Add("#sit", OleDbType.VarWChar).Value = txt_site.Text;
command.Parameters.Add("#grp", OleDbType.VarWChar).Value = txt_group.Text;
command.Parameters.Add("#knd", OleDbType.VarWChar).Value = txt_kind.Text;
command.Parameters.Add("#uni", OleDbType.VarWChar).Value = txt_unit.Text;
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
The parameters collection is filled with the values required by your query text. Notice that I don't know exactly the datatype of your columns in the database. The parameter OleDbType should exactly match the types expected to avoid Type Mismatch exceptions
Last tip. Connections should be created, opened and closed when needed. Do not keep a global connection object. You don't get much gain in performance because ADO.NET employs a technique called Connection Pooling
I am new on c# and i am facing problem. i made two buttons, one for case another for credit card. when i click on button, my data is not inserting into ms access file.why is it not showing any error and how can i fix it ?
private void CashButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.Cash);
}
private void CreditCardButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.CreditCard);
}
private void SaveOrder(int paymentType)
{
try
{
string connstring = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [Orders](OrderNummber,TransactionDate,ClientName,TotalAmount,PaymentType) VALUES(#OrderNummber,#TransactionDate,#ClientName,#TotalAmount,#PaymentType)",conn))
{
cmd.Parameters.AddWithValue("#OrderNummber",OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#TransactionDate",TransactionDateDateTimePicker.Value.Date);
cmd.Parameters.AddWithValue("#ClientName",ClientNameTextBox.Text);
cmd.Parameters.AddWithValue("#TotalAmount",Convert.ToDecimal(TotalAmountTextBox.Text));
cmd.Parameters.AddWithValue("#PaymentType", paymentType);
cmd.ExecuteNonQuery();
}
foreach (DataGridViewRow row in CartDataGridView.Rows)
{
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [OrdersItems](OrderNumber,Quantity,UnitPrice,TotalPrice) VALUES(#OrderNumber,#Quantity,#UnitPrice,#TotalPrice)", conn))
{
cmd.Parameters.AddWithValue("#OrderNumber", OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt16(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#UnitPrice",Convert.ToDecimal(row.Cells["UnitPrice"].Value));
cmd.Parameters.AddWithValue("#TotalPrice", Convert.ToDecimal(row.Cells["TotalPrice"].Value));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Order is processed successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
}
}
Do it like this.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
This will definitely work. Just change the connection string and the variables to suit your needs.
Here is a sample image of the UI:
I'm working on a project that will import an Excel file and display the data to a DataGridView via Windows form. Importing the Excel file and displaying it in the DataGridView works fine, what I'm having issues is saving the data in the DataGridView as a bulk insert when I click on the Save button it shows an
Screenshot of the error:
An unhandled exception of type 'System.ArgumentException' occured in System.Data.dll
When I view details it shows :
No mapping exists from object type System.Windows.Forms.DataGridViewTextBoxColumn to a known managed provider native type.
Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
SAVE BUTTON CODE
private void btn_Save_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string constring = #"Data Source=databasename;Initial Catalog=Rookies;Integrated Security=True";
using(SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO tbl_prospects ([prospectid], [firstname], [lastname], [height], [weight], [age], [college])VALUES(#prospectid, #firstname, #lastname, #height, #weight, #age, #college)", con))
{
cmd.Parameters.AddWithValue("#prospectid", prospectidDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#firstname", firstnameDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#lastname", lastnameDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#height", heightDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#weight", weightDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#age", ageDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#college", collegeDataGridViewTextBoxColumn);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
MessageBox.Show("Successfully Saved!");
}
}
}
I also included the other codes below
BROWSE BUTTON CODE
private void btn_Browse_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.txt_Path.Text = openFileDialog1.FileName;
}
}
LOAD BUTTON CODE
private void btn_Load_Click(object sender, EventArgs e)
{
string PathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txt_Path.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + txt_Sheet.Text + "$]", conn);
DataTable DT = new DataTable();
myDataAdapter.Fill(DT);
dataGridView1.DataSource = DT;
}
I'm new on coding C# and trying to learn it, this will be my first application if ever, if anyone can help me what I need to do thanks in advance.
You can directly use SqlBulkCopy to write datatable to Sql Server, rather than doing it row by row.
string constring = #"Data Source=databasename;Initial Catalog=Rookies;Integrated Security=True";
using (var bulkCopy = new SqlBulkCopy(constring ))
{
bulkCopy.BatchSize = 500;
bulkCopy.NotifyAfter = 1000;
bulkCopy.DestinationTableName = "TableName";
bulkCopy.WriteToServer(dataTable);
}
There are various SqlBulkCopy constructors to pass SqlConnection and SqlTransaction as well.
you can get the values from each row like this
foreach (DataGridViewRow row in dataGridView.Rows)
{
// your code
cmd.Parameters.AddWithValue("#prospectid",row.Cells["ColumnName"].Value.ToString());
}
My first remark: use only 1 times the object SqlConnextion and it is better now to add SqlTransaction object to avoid the partial recording of data in case of error on a line of DataGridView.
for the answer you need to specify the value of the cell of each column
private void btn_Save_Click(object sender, EventArgs e)
{
string constring = #"Data Source=databasename;Initial Catalog=Rookies;Integrated Security=True";
SqlConnection con = new SqlConnection(constring);
SqlTransaction transaction = con.BeginTransaction();
try
{
con.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO tbl_prospects ([prospectid], [firstname], [lastname], [height], [weight], [age], [college])VALUES(#prospectid, #firstname, #lastname, #height, #weight, #age, #college)", con))
{
cmd.Parameters.AddWithValue("#prospectid", row.Cells["prospectid"].Value);
cmd.Parameters.AddWithValue("#firstname", row.Cells["firstname"].Value);
cmd.Parameters.AddWithValue("#lastname", row.Cells["lastname"].Value);
cmd.Parameters.AddWithValue("#height", row.Cells["height"].Value);
cmd.Parameters.AddWithValue("#weight", row.Cells["weight"].Value);
cmd.Parameters.AddWithValue("#age", row.Cells["age"].Value);
cmd.Parameters.AddWithValue("#college", row.Cells["college"].Value);
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();
}
}
transaction.Commit();
con.Close();
MessageBox.Show("Successfully Saved!");
}
catch (Exception ex)
{
transaction.Rollback();
con.Close();
MessageBox.Show(ex.Message);
}
}
private void btn_Insert_Click(object sender, EventArgs e)
{
if (txtSearsh.Text != "")
{
if (dataGridView1.Rows.Count > 0)
{
for (int i = 0; i < dataGridView1.Rows.Count ; i++)
{
COI.INSERTdATA(txtSearsh.Text,
dataGridView1.CurrentRow.Cells["COIL_NO"].Value.ToString(),
dataGridView1.CurrentRow.Cells["SLAB_NO"].Value.ToString(),
dataGridView1.CurrentRow.Cells["ORDER_NO"].Value.ToString(),
dataGridView1.CurrentRow.Cells["ORDER_NO"].Value.ToString(),
dataGridView1.CurrentRow.Cells["ITEM_NO"].Value.ToString(),
dataGridView1.CurrentRow.Cells["PROD_TYPE"].Value.ToString(),
dataGridView1.CurrentRow.Cells["GRADE"].Value.ToString(),
dataGridView1.CurrentRow.Cells["SL_THICK"].Value.ToString(),
dataGridView1.CurrentRow.Cells["SL_WIDTH"].Value.ToString(),
dataGridView1.CurrentRow.Cells["SL_LENGTH"].Value.ToString(),
dataGridView1.CurrentRow.Cells["SL_WGHT"].Value.ToString(),
dataGridView1.CurrentRow.Cells["C_THICK"].Value.ToString(),
dataGridView1.CurrentRow.Cells["C_WIDTH"].Value.ToString(),
dataGridView1.CurrentRow.Cells["C_WT"].Value.ToString(),
dataGridView1.CurrentRow.Cells["PRODUCED"].Value.ToString(), "", "", "", "", "", "", DTP.Value, "", "", "", "", "", ""
);
}
MessageBox.Show("SaccessFouly");
}
else { MessageBox.Show("أدخل رقم البرنامج"); }
}
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=asa-PC\\SQLEXPRESS;Initial Catalog=table1;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("select * from worker where number='" + textBox1.Text.Trim() + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr[0].ToString();
textBox3.Text = dr[1].ToString();
MessageBox.Show("No record is found with this number >> " + textBox1.Text.ToString());
}
}
}
}
hello guys can you help me with this
i need the MessageBox to show this message if No record is found but i don't know how to include the IF with the code
and a max numbers or letters for textbox1 is 10 if the user put more then the MessageBox (max10) will appear
You can use SqlDataReader.HasRows property to determine whether any records were returned. like:
if (dr.HasRows)
{
while (dr.Read())
{
textBox2.Text = dr[0].ToString();
textBox3.Text = dr[1].ToString();
}
}
else
{
MessageBox.Show("No record is found with this number >> " + textBox1.Text.ToString());
}
But couple of other things to add:
Use SqlParamaters instead of concatenation queries, you are open to SQL Injection.
Not really sure how would you accomplish showing more than one record in TextBox controls you probably need a Grid or add your returned rows/recrods to a List<T> or List<Worker> where Worker class can have properties for columns.
Use using statement with SqlCommand/SqlConnection and SqlDataReader as they implement IDisposable
this dr[0].ToString() could potentially throw Null Reference Exception, research and see how you can safeguard it.
So your code more or less should look like:
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = "Data Source=asa-PC\\SQLEXPRESS;Initial Catalog=table1;Integrated Security=True";
con.Open();
using (SqlCommand cmd = new SqlCommand("select * from worker where number=#Number", con))
{
cmd.Parameters.AddWithValue("#Number", textBox1.Text);//or explicity specify type using .Add
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
//Add to List<Worker> with properties Name and Number etc
textBox2.Text = dr[0].ToString();
textBox3.Text = dr[1].ToString();
}
}
else
{
MessageBox.Show("No record is found with this number >> " + textBox1.Text.ToString());
}
}
}
}
}