Prevent duplicate entry in database - c#

private void Save_Click(object sender, EventArgs e)
{
string strconn = #"Server=.\SQLEXPRESS;initial catalog=PharmacyV2;integrated security=true;";
SqlConnection conn = new SqlConnection(strconn);
//SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from Units",conn);
da.Fill(ds, "Units");
bool found = false;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < ds.Tables["Units"].Rows.Count; j++)
{
if (ds.Tables["Units"].Rows[j][0].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString())
{
found = true;
break;
}
}
if (found==false)
{
SqlCommand cmd;
cmd = new SqlCommand("insert into Units (Unit_name) values (#name)", conn);
cmd.Parameters.AddWithValue("#name", dataGridView1.Rows[i].Cells[0].Value.ToString());
cmd.ExecuteNonQuery();
MessageBox.Show("تمت الاضافه");
}
}
conn.Close();
}
my program compare the each element from datagridview with every element from Uint table from database to prevent duplicate in database
if element from datagridvoew is not Similar to element in uint table in database
implement insert statement
Why the program does not insert any data to database?
(Does not implement the insert statement )

initialise your found variable to false inside your first for loop :
found = false;
so that it will be set to initial state for every iteration. otherwise if once it is set to true always becomes true.thats why yor insert statement is not getting executed.
So your for loop should look like :
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
found = false;
for (int j = 0; j < ds.Tables["Units"].Rows.Count; j++)
{
if (ds.Tables["Units"].Rows[j][0].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString())
{
found = true;
break;
}
}
if (found==false)
{
SqlCommand cmd;
cmd = new SqlCommand("insert into Units (Unit_name) values (#name)", conn);
cmd.Parameters.AddWithValue("#name", dataGridView1.Rows[i].Cells[0].Value.ToString());
cmd.ExecuteNonQuery();
MessageBox.Show("تمت الاضافه");
}
}

How about you ask the database to check if the entry exists?
var unitName = dataGridView1.Rows[i].Cells[0].Value.ToString();
var command = new SqlCommand("SELECT COUNT(*) FROM Units WHERE Unit_name = #name", connection);
command.Parameters.AddWithValue("#name", unitName);
int result = (int)command.ExectureScalar();
if(result == 0) // no entry
{
//Insert.
}

Related

Datatable C# Input string was not in a correct format

My code:
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
String gtennha = cmd.ExecuteScalar().ToString();
dt.Rows[i][1] = gtennha;
}
When I run code, I received an error. Please help me fix it.
Expected Type as Int32
If gtennha contains a number, you can parse it to an int. With more safeguards:
var gtennha = cmd.ExecuteScalar();
try
{
if(gtennha != null)
dt.Rows[i][1] = int.Parse(gtennha.ToString());
else
Console.WriteLine("Error: Query didn't return a result.");
}
catch(FormatException ex)
{
Console.WriteLine("Error: Couldn't parse 'gtennha' to a number.");
/* more error handling */
}
Parse string to int
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
String gtennha = cmd.ExecuteScalar().ToString();
int a;
int.TryParse(gtennha, out a);
dt.Rows[i][1] = a;
}
Update
if gtennha always start with VIOFFICE or a word something like that then use this way split string
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
String gtennha = cmd.ExecuteScalar().ToString();
int a;
int.TryParse(gtennha.Split(' ')[1], out a);
dt.Rows[i][1] = a;
}
I think you have choosen the wrong column to assign the return value of your ExecuteScalar query. From your error message it is clear that the return value is a string "VI BUILDING 29BD" (or something like that) and you are trying to assing that value to the same column dt.Rows[i][1] that you have used as the source for the ID parameter. This of course cannot be correct.
So you need to identify what is the column that you want to assign the return value of the ExecuteScalar and take extra care on handling that return value that could be NULL if there is no match on the WHERE clause
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
object result = cmd.ExecuteScalar();
// SUPPOSE THAT YOU WANT TO ASSIGN AT COLUMN 2 NOT STILL AT COLUMN 1
if(result != null)
dt.Rows[i][2] = gtennha;
}

Check row length if greater then 0 then print data and while printing add for (i = 0; i <= dt.Rows.Count - 1; i++)

Iam trying to print data base value and the radio buttons in to a div but my problem is first if there are no rows in the table i need to show that there are no rows and the second probllem i want to add for (i = 0; i <= dt.Rows.Count - 1; i++) for condition as am using radio buttons that are dynamically generated i need to add i means number to each fetch.
string xxx= SessionManager.xxxxxxxx;
string htmlStr = "";
using (MySqlConnection myConnection = new MySqlConnection(constr))
{
string oString = "Select * from xxxxx WHERE xxxx=#xxxx and xxxx=#xxxx ";
MySqlCommand oCmd = new MySqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#xxxx", "0");
oCmd.Parameters.AddWithValue("#xxxx", "0");
myConnection.Open();
using (MySqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
string Name = oReader["xxxx"].ToString();
// string Pass = oReader["xxxx"].ToString();
htmlStr += "<tr><td>" + Name + "</td><td><input type='radio' name='Present' value='Present'></td><td><input type='radio' name='Absent' value='Absent'></td><td><input type='radio' name='Leave' value='Leave'></td></tr>";
}
myConnection.Close();
}
}
STUDENT_LIST.InnerHtml = htmlStr;
MySqlDataReader has a readonly property called as "HasRows". The usage of it is;
if(oReader.HasRows)
{
// Perform operation
}
else
// Some other operation
The link for detailed list of members and methods of MySqlDataReader is here
UPDATE:
If you are looking for an example for the usage of MySqlDataAdapter, I would suggest you to go through the DataSet & MySqlDataAdapter section of this link
Hope this helps.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("select * from your_table", con);
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
int num = ds.Tables[0].Rows.Count;
for (int i = 0; i < num - 1; i++)
//Do something here
}
catch (Exception ex)
{
//...
}
finally
{
con.Close();
}
Hope it helps

Index was outside the bounds of the array. c# OleDbDataReader

Could someone please tell me what I am doing wrong here. I have compiled my code and I get it to read the ROWS and return the count. However, I get an error when saying the "Index was outside the bounds of the array" when I pass it to this line of code: rowData += dbReader.GetValue(iRow).ToString();
//Create SQL strings
string sql = "SELECT 'Computers' FROM [Sheet1$]";
//Create the instances
OleDbConnection dbConnection;
OleDbDataAdapter dbAdapter;
OleDbCommand dbCommand;
OleDbDataReader dbReader;
DataTable dataTable;
//Call the instance
dbConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + #"\\slcnpr97\Desktop\Game Changers\\computers.xls" + "';Extended Properties='Excel 12.0 Xml;HDR=YES'");
dbConnection.Open();
dbAdapter = new OleDbDataAdapter(sql, dbConnection);
dbCommand = new OleDbCommand(sql, dbConnection);
dataTable = new DataTable();
dbReader = dbCommand.ExecuteReader();
dbAdapter.Fill(dataTable);
//Method Variable
int iRow = dataTable.Rows.Count;
string rowData = null;
while (dbReader.Read())
{
for (int i = 0; i < iRow; i++)
{
rowData += dbReader.GetValue(iRow).ToString();
}
}
//Close Connections
dbReader.Close();
dbConnection.Close();
MessageBox.Show(rowData);
You should modify
int iRow = dataTable.Rows.Count;
to
int numFields = dbReader.FieldCount;
Your for loop then becomes
for (int i = 0; i < numFields; i++)
{
rowData += dbReader.GetValue(numFields).ToString();
}
try with (Set dbReader.GetValue(0).ToString())
while (dbReader.Read())
{
for (int i = 0; i < iRow; i++)
{
rowData += dbReader.GetValue(0).ToString();
}
}

how get all records on database using mysql?

I tried this:
MySqlConnection con = new MySqlConnection(...);
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM questions;";
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
int i = 0, len = reader.FieldCount;
while (i < len)
{
Response.Write(reader.GetString(i));
i++;
}
returns only the first values from table. how get all?
thanks in advance
You have to call reader.Read() until it returns false.
I've also taken the liberty of converting your inner loop to a for loop.
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Response.Write(reader.GetString(i));
}
}
Read this to read up on the IDataReader : http://msdn.microsoft.com/en-us/library/system.data.idatareader.read.aspx

Trying to insert datagridview into SQL Server database

I am trying to import my datagridview data into my SQL Server database, But I am getting an error
Failed to convert parameter value from a DataGridView TextVoxCell to a variabletype
Can someone please guide me on a right path?
for (int r = 1; r < dataGridView1.Rows.Count; r++)
{
for (int c = 1; c < dataGridView1.Columns.Count; c++)
{
try
{
SqlConnection con = new SqlConnection(constring);
SqlCommand query = new SqlCommand("INSERT into RosterTest (EmployeeID, Date, ShiftType) Values (#EmployeeID,#Date,#ShiftType", con);
query.Parameters.Add("#EmployeeID", SqlDbType.Int).Value = dataGridView1.Columns[c].HeaderText;
query.Parameters.Add("#Date", SqlDbType.Date).Value = dataGridView1.Rows[r].Cells[0];
query.Parameters.Add("ShiftType", SqlDbType.NVarChar).Value = dataGridView1.Rows[r].Cells[c];
con.Open();
query.ExecuteNonQuery();
}
}
}
Try adding Value to your cell, it's the property containing the information.
query.Parameters.Add("#Date", SqlDbType.Date).Value = dataGridView1.Rows[r].Cells[0].Value;
Added .Value to my query Parameters. Inserting now works!
for (int r = 0; r < dataGridView1.Rows.Count; r++)
{
for (int c = 1; c < dataGridView1.Columns.Count; c++)
{
try
{
SqlConnection con = new SqlConnection(constring);
SqlCommand query = new SqlCommand("INSERT into RosterTest (EmployeeID, Date, ShiftID) Values (#EmployeeID,#Date,#ShiftID)", con);
query.Parameters.Add("#EmployeeID", SqlDbType.Int).Value = dataGridView1.Columns[c].HeaderText;
query.Parameters.Add("#Date", SqlDbType.Date).Value = dataGridView1.Rows[r].Cells[0].Value;
query.Parameters.Add("#ShiftID", SqlDbType.NVarChar).Value = dataGridView1.Rows[r].Cells[c].Value;
con.Open();
query.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Categories

Resources