what is wrong with this code what i am actually to achieve is
insert rows to database clear the textbox value and enter another record..
the problem is at first loop data will be added successfully...but on the next iteration loops it will add empty strings to the rows of database but what i want is accept input from textbox and continue iterating...please try to read the code and help me ...it is been 2 weeks since am trying so solve this ..
again what i want to do
-user enter number of group members
- the group members have column like ,first name,last name gender,city.etc
FOR all the group members (eg:6 group membrs) add 6 rows of of different column will be added
but my code does is add the first rows and the rest 5 row's will be empty data
Sorry for my bad english..somebody please try to think what i am thinking
{{
private void btnAddloan_Click(object sender, RoutedEventArgs e)
if (txtname.Text != "" && txtlname.Text != "")
{
int c=0;
int input=int.Parse(txttotalnumberofgroupmembers.Text);
do
{
string connstr = "Data Source=GER-PC\\PLEASEGOD;Initial Catalog=ACSI;Integrated Security=True";
SqlConnection con = new SqlConnection(connstr);
con.Open();
SqlCommand cmd = new SqlCommand("insert into Customer(FirstName,LastName) values(#n,#p)", con);
cmd.Parameters.AddWithValue("#p", txtname.Text);
cmd.Parameters.AddWithValue("#n", txtlname.Text);
cmd.ExecuteNonQuery();
con.Close();
lblnotify.Content = c + 1 + "" + "members added";
//clear textbox values and wait for another input
txtname.Text = "";
txtlname.Text = "";
if (txtname.Text != "" && txtlname.Text != "")
{
continue;
}
else
{
MessageBoxResult result =MessageBox.Show("procces","Continue Adding Memebers",MessageBoxButton.YesNoCancel,MessageBoxImage.Warning);
//txtname.Text = s;
//txtlname.Text= s1;
//MessageBox.Show();
switch (result)
{
case MessageBoxResult.Yes:
if (txtname.Text != "")
{
}
else
{
}
break;
case MessageBoxResult.No:
break;
case MessageBoxResult.Cancel:
break;
}
}
c++;
} while (c < input);
}
else
{
MessageBox.Show("plese fill first name and last name");
}
}
You're clearing the txtname.Text and txtlname.Text value after you do the insert. In the next iteration you're recreating the Parameters, but this time your text values are EMPTY.
txtname.Text = "";
txtlname.Text = "";
Instead of recreating your command object, why not just execute the command object N times. Like:
SqlCommand cmd = new SqlCommand("insert into Customer(FirstName,LastName) values(#n,#p)", con);
cmd.Parameters.AddWithValue("#p", txtname.Text);
cmd.Parameters.AddWithValue("#n", txtlname.Text);
for(int i = 0; i < input; i++)
{
cmd.ExecuteNonQuery();
}
Related
I am looking in my code if connected user has insert or update permission, stated in the SQL Server. If user has INSERT permission, editing previously saved records in table in datagridview is disabled, and only adding new rows is enabled. And if user has both INSERT or UPDATE permission, user can edit any records in table. My code works great if user has only INSERT permision but if he has both insert and update, i dont know how to cancel that if loop.
Here is my code for CellBeginEdit:
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
string db2 = Text1;
string user2 = Text2;
string pass2 = Text3;
string selected = this.ComboBox1.GetItemText(this.ComboBox1.SelectedItem);
using (SqlConnection SqlConn = new SqlConnection(#"Data Source=server;Initial Catalog =" + db2 + "; User ID =" + user2 + "; Password =" + pass2 + ""))
{
SqlConn.Open();
SqlCommand SqlCmd2 = new SqlCommand();
SqlCommand SqlCmd3 = new SqlCommand();
SqlCmd2.Connection = SqlConn;
SqlCmd3.Connection = SqlConn;
SqlCmd2.CommandText = "SELECT isnull(has_perms_by_name('" + db2 + ".dbo." + selected + "', 'OBJECT', 'INSERT'), 0)";
SqlCmd3.CommandText = "SELECT isnull(has_perms_by_name('" + db2 + ".dbo." + selected + "', 'OBJECT', 'UPDATE'), 0)";
Int32 number2 = (Int32)SqlCmd2.ExecuteScalar();
Int32 number3 = (Int32)SqlCmd3.ExecuteScalar();
if (number2 == 1)
{
if (!dataGridView1.Rows[e.RowIndex].IsNewRow)
{
if (e.RowIndex < dataGridView1.NewRowIndex)
{
if (AddedRowIndex != e.RowIndex)
{
MessageBox.Show("Not allowed to edit previous records!");
e.Cancel = true;
}
}
}
}
else if ((number2 == 1) && (number3 == 1))
{
//enable editing of all records in table
}
SqlConn.Close();
}
}
The problem appears to be that you're checking for the more simple condition first, and it's going to be true for both Insert and Update, which means the else if condition is never checked and your enable-update code never runs.
Instead, you should check the compound condition first, and if that's false, then check the single condition.
For example:
if (number2 == 1 && number3 == 1)
{
// enable editing of all records
}
else if (number2 == 1)
{
// enable insert only
}
or another option, since they share a condition:
if (number2 == 1)
{
if (number3 == 1)
{
// enable editing of all records
}
else
{
// enable insert only
}
}
I'm having a little bit of a problem with this code. I'm trying to make a code that reads a text from textbox and adds words to database word by word. If word already exist in database, it should increase the number of count that word was added to database, if word doesn't exist, it should add the to database.
Everything is working fine on its own perfectly, but when I input words that exist in database and new words at the same time problem occurs. Code increases count number for existing words as it should, but simply doesn't add new words to the database. And I'm not getting any error.
How to make sure that both functions work at the same for new and old words?
SqlConnection con = new SqlConnection(ConStr);
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
string raw = rawtxt.Text.ToString();
string[] rawwords = raw.Split(' ');
foreach (var rawword in rawwords)
{
string mon_s = "Select * From Dict";
SqlCommand mon_search = new SqlCommand(mon_s, con);
SqlDataReader srd = mon_search.ExecuteReader();
while (srd.Read())
{
if (srd[1].ToString() == rawword)
{
flag = true;
break;
}
}
srd.Close();
if (flag == false)
{
string raw_lat_c = rawword.Replace("а", "a").Replace("б", "b").Replace("в", "v").Replace("г", "g").Replace("д", "d").Replace("е", "e").Replace("ё", "e").Replace("ж", "j").Replace("з", "z").Replace("и", "i").Replace("й", "i").Replace("к", "k").Replace("л", "l").Replace("м", "m").Replace("н", "n").Replace("о", "o").Replace("ө", "u").Replace("п", "p").Replace("р", "r").Replace("с", "s").Replace("т", "t").Replace("у", "u").Replace("ү", "u").Replace("ф", "f").Replace("х", "h").Replace("ц", "ts").Replace("ч", "ch").Replace("ш", "sh").Replace("щ", "sh").Replace("ъ", "i").Replace("ы", "i").Replace("ь", "i").Replace("э", "e").Replace("ю", "yu").Replace("я", "ya");
int count = 1;
string ins = "Insert into Dict (mongol, latin, count) values(N'" + rawword + "','"+ raw_lat_c +"', '" + count + "')";
SqlCommand command_ins = new SqlCommand(ins, con);
command_ins.ExecuteNonQuery();
}
if (flag == true)
{
string upd_count = "Update Dict Set count=count+1 Where mongol=N'" + rawword + "'";
SqlCommand command_upcnt = new SqlCommand(upd_count, con);
command_upcnt.ExecuteNonQuery();
}
}
}
You have to reset the value of "flag" in every foreach statement. So, before the while, you should do add SqlDataReader srd = mon_search.ExecuteReader(); - like this:
[...]
SqlDataReader srd = mon_search.ExecuteReader();
flag = false;
while (srd.Read())
{
if (srd[1].ToString() == rawword)
{
flag = true;
break;
}
}
[...]
What you are doing now is that once one word in "rawwords" is found in your database, all the remaining words will always be "repeated" because your flag will neve be false.
Change your code like This
if (srd[1].ToString() == rawword)
{
flag = true;
break;
}
else
{
flag = false;
}
I'm making a windows form where in all the checkedlist values are stored in one row. However it only stores one value.
Question is, is it possible to store all the checkedlist values in a single row in which only their assigned ids are stored?
This is my previous code below. if you find any mistakes or if you have any idea on how to edit to make it work, it would be a big help for me. Thanks!
foreach (DataRowView item in this.checkedListBox1.CheckedItems)
{
NpgsqlCommand cmd = new NpgsqlCommand("Insert into name(eid, name, famid) Values (#eid, #name, #famid)", conn);
cmd.Parameters.AddWithValue("#eid", textBox1.Text);
cmd.Parameters.AddWithValue("#name", textBox2.Text);
string value = item.Row[0].ToString().Split(',');
cmd.Parameters.AddWithValue("#famcon", value);
cmd.ExecuteNonQuery();
}
Since you are using C#, use this code but gotta change the default name to yours.
private void button1_Click(object sender, EventArgs e)
{
try
{
string Str = "";
if (checkedListBox1.CheckedItems.Count > 0)
{
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
if (Str == "")
{
Str = checkedListBox1.CheckedItems[i].ToString();
label1.Text = Str;
}
else
{
Str += ", " + checkedListBox1.CheckedItems[i].ToString();
label1.Text = Str;
}
}
// Make your connection to the DataBase and insertion code starting within that area.
MessageBox.Show("Your selection is for :" + Str);
}
else
{
MessageBox.Show("Please select one name at least to work it out!");
}
while (checkedListBox1.CheckedItems.Count > 0)
{
checkedListBox1.SetItemChecked(checkedListBox1.CheckedIndices[0],false);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.ToString());
}
}
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("insert into reg (name,num,gender,qual) values
(#name,#num,#gender,#qual)", con);
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#num", TextBox2.Text);
cmd.Parameters.AddWithValue("#gender",
RadioButtonList1.SelectedItem.ToString());
for (int i = 0; i < CheckBoxList1.Items.Count - 1;i++ )
{
if(CheckBoxList1.Items[1].Selected)
{
string var = string.Empty;
var += CheckBoxList1.Items[1].Text.ToString();
cmd.Parameters.AddWithValue("#qual",var);
}
}
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert(
'record has been added');</script>");
}
catch (Exception er)
{
Response.Write("<script language='javascript'>alert(
'conncetion error');</script>");
}
finally
{
con.Close();
}
I am beginner of asp.net. I don't know how to save the checkboxlist values to data base. I the above code it saves only the last value. Please help me, thanks in advance...
You are iterating through loop but only comparing value 1 all the time I have changed 1 to i.
And I think you need to collect values and and them all only once.To perfoem that I have moved cmd.Parameters.AddWithValue("#qual",s); statement out of for loop
Note: I am separating values with ',' I don't know that is your business need or not
string s;
for (int i = 0; i < CheckBoxList1.Items.Count - 1;i++ )
{
if(CheckBoxList1.Items[i].Selected)//changed 1 to i
s += CheckBoxList1.Items[i].Text.ToString() + ","; //changed 1 to i
}
cmd.Parameters.AddWithValue("#qual",s);
It's because you're only executing the command once, outside of the for-loop.
If you move the Execute query into the for loop it should work.
Note that this will fix your code, but it will neither safe or optimal.
I'm getting a "syntax error" while using the code below.
it suppoused to avoid adding row when you entered all the values of this specific protein(it is a project combined Biology and Programming.
'serialPro' is a textbox which contains a number,but saved as string.
'Reset_Click' resetes all textboxes.
THE CODE:
if ((serialPro.Text == String.Empty) || (codon1.Text == String.Empty))
{
MessageBox.Show("You didn't fill all the fields","Attention"
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
Reset_Click(sender, e);
}
else
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
string mySQL = " SELECT COUNT(tblOrderAA.orderAASerialPro) AS orderAASerialPro1 FROM tblOrderAA" +
"WHERE tblOrderAA.orderAASerialPro=" + Convert.ToInt32(serialPro.Text) +
" SELECT (tblProInfo.proInfoSerialNum) FROM tblProInfo WHERE tblProInfo.proInfoSerialNum=" +
Convert.ToInt32(serialPro.Text);
OleDbCommand datacommand = new OleDbCommand(mySQL, myConnection);
OleDbDataReader dataReader = datacommand.ExecuteReader();
dataReader.Read();
if (dataReader.GetInt32(0) == dataReader.GetInt32(1))
{
MessageBox.Show("You have entered all the amino acids for this protein", "Attention",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
Reset_Click(sender, e);
}
TNX for the help!
I'm not sure if having two select statements in your MySQL query is valid or not, or why you're taking a string only to turn it into a number so you can add it to another string, but this is probably the cause of the syntax error.
" SELECT COUNT(tblOrderAA.orderAASerialPro) AS orderAASerialPro1 FROM tblOrderAA" +
"WHERE tblOrderAA.orderAASerialPro=" + Convert.ToInt32(serialPro.Text) +
The way you're concatenating this string means there would be no space between tblOrderAA and WHERE. Add a space in between.
You should also look up SQL injection/parameterized queries.
First, the way you have it setup, even if it were supported by access, would require you to process different resultset (you would have to call Reader.NextResult in order to get the values from the second select statement.
However, this is an easy problem to solve: break your queries up into separate commands and just get the one value from each query that you are looking for:
int TotalCompleted;
int TotalToComplete;
string mySQL;
OleDbCommand datacommand;
object oValue;
mySQL = " SELECT COUNT(tblOrderAA.orderAASerialPro) AS orderAASerialPro1 FROM tblOrderAA WHERE tblOrderAA.orderAASerialPro=" + Convert.ToInt32(serialPro.Text);
datacommand = new OleDbCommand(mySQL, myConnection);
oValue = datacommand.ExecuteScalar();
if (oValue != DBNull.Value)
{
TotalCompleted = (int)oValue;
} else
{
TotalCompleted = 0;
}
mySQL = "SELECT tblProInfo.proInfoSerialNum FROM tblProInfo WHERE tblProInfo.proInfoSerialNum=" + Convert.ToInt32(serialPro.Text);
datacommand = new OleDbCommand(mySQL, myConnection);
oValue = datacommand.ExecuteScalar();
if (oValue != DBNull.Value)
{
TotalToComplete = (int)oValue;
} else
{
TotalToComplete = 0;
}
if (TotalCompleted == TotalToComplete)
{
MessageBox.Show("You have entered all the amino acids for this protein", "Attention",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
Reset_Click(sender, e);
}