how can i merge two field in combobox - c#

this is my code :
cmbSahebFa.Items.Clear();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select mID,mName from tblMoshtari";
objCon.Connecting();
cmd.Connection = objCon.con;
objCon.con.Open();
try
{
SqlDataReader objDataReader = cmd.ExecuteReader();
object[] x = new object[2];
while (objDataReader.Read())
{
objDataReader.GetSqlValues(x);
cmbSahebFa.Items.Add(x[1].ToString());
}
}
catch (Exception exp)
{
MessageBox.Show("Error") : " + exp.Message);
}
finally
{
objCon.con.Close();
}
i want to display both field in combo box.
how can i show two field mID+mName in combobox ?

cmbSahebFa.Items.Add(objDataReader[0].ToString() + " " + objDataReader[1].ToString());
or
SqlDataReader objDataReader = cmd.ExecuteReader();
object[] x = new object[2];
while (objDataReader.Read())
{
objDataReader.GetSqlValues(x);
cmbSahebFa.Items.Add(x[0].ToString()+ " " + x[1].ToString());
}
or by column name
SqlDataReader objDataReader = cmd.ExecuteReader();
while (objDataReader.Read())
{
cmbSahebFa.Items.Add(objDataReader["mID"].ToString() + " " + objDataReader["mName"].ToString());
}
Here is MSDN Reference on Retrieving Data Using DataReader.

I think, SQL concatination would be easier:
cmd.CommandText = "select mID + ' ' + mName from tblMoshtari";

Related

Update SQL Server table columns with button click from gridview fields

I have a gridview that displays all the fields from my table.
My problem is that I need to update my SQL Server table when I click the save button (onclick) because I added a new field that generates a unique ID to every Item I have in my table. And It will add the generated id to the database table whenever I click the save button.
I have tried this
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text +
"' , [prno], [itemaname], [specification], [qty], [uomid], [expenseid],
[statusid], [userid], [inserteddate], [withquotation], [potempid] WHERE
idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
But I get an error
Here is my complete code:
public void SaveTogrdPOTemp()
{
SqlConnection ConnString = new SqlConnection(ConfigurationManager.ConnectionStrings["MUCS2.0ConnectionString"].ConnectionString);
string strSql = string.Empty;
pextid = "TPID";
using (SqlCommand cmd = new SqlCommand("SELECT * FROM GenIDGen WHERE extid = '" + pextid + "'"))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = ConnString;
ConnString.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
var extid = sdr["extid"].ToString().Trim();
var genID = sdr["generatedid"].ToString().Trim();
var gentr = sdr["generator"].ToString();
var potempoid = extid + genID;
ConnString.Close();
}
}
strSql = "UPDATE [dbo].[GenIDGen] SET [generator] = generator + 1
WHERE extid = '" + pextid + "' ";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text + "' WHERE idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
}
For the generating of ID and the updating of the gridview. Thank you!

sqlite database is locked C#

So i have this "database is locked" exception since yesterday. Tried everything i found here, yet still nothing. I'm using two forms - simple login form and then another one, where user can add new product to database. Checking if product already exist in db works, but adding new one throws that exception. Check it out please:
try
{
using (SqliteConnection db = new SqliteConnection("Filename=Magazyn.sqlite"))
{
db.Open();
string SQLcheck = "select * from Administrator";
using (SqliteCommand cmd = new SqliteCommand(SQLcheck, db))
{
using (SqliteDataReader reader = cmd.ExecuteReader())
{
var count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count > 0 && textBox1 != null && !string.IsNullOrWhiteSpace(textBox1.Text))
{
string sql = "select * from Administrator WHERE Name='" + textBox1.Text +
"' AND Password ='" + textBox2.Text + "'";
using (SqliteCommand command = new SqliteCommand(sql, db))
{
using (SqliteDataReader rdr = command.ExecuteReader())
{
if (rdr.Read())
{
MessageBox.Show(textBox1.Text + ", zostałeś pomyślnie zalogowany", "Logowanie");
AddProduct a = new AddProduct();
a.ShowDialog();
this.Close();
return;
}
else
{
MessageBox.Show("Nie ma administratora o loginie " + textBox1.Text +" lub Twoje hasło jest niepoprawne", "Błąd logowania");
textBox1.Clear();
textBox2.Clear();
}
}
}
}
else if (count == 0)
{
MessageBox.Show(
"W systemie nie istnieje konto administratora - nastąpi przekierowanie do formularza rejestracyjnego",
"Pierwsze logowania - konieczna rejestracja");
AddAdmin a = new AddAdmin();
a.ShowDialog();
return;
}
}
}
db.Close();
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
And 2nd Form:
try
{
using (SqliteConnection db = new SqliteConnection("Filename = Magazyn.sqlite"))
{
db.Open();
string sqlCheck = "select * from Produkty WHERE RFID='" + RFID.Text + "'";
using (SqliteCommand cmd = new SqliteCommand(sqlCheck, db))
{
using (SqliteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
MessageBox.Show("W bazie produktów jest już produkt o podanym tagu RFID", "Wykryto duplikat");
RFID.Clear();
}
else
{
reader.Close();
reader.Dispose();
string sql = "INSERT INTO Produkty (Name, RFID, Price, Unit, VAT) values ('" + Nazwa.Text + "','" +
RFID.Text + "','" + Cena.Text + "','" + Jednostka.Text + "','" + VATcat + "');";
//string sql = #"INSERT INTO Produkty (Name, RFID, Price, Unit, VAT) values (#name, #RFID, #price, #unit, #vat)";
using (SqliteCommand command = new SqliteCommand(sql, db))
{
using (SqliteDataReader rdr = command.ExecuteReader())
{
MessageBox.Show("Pomyślnie dodano produkt " + Nazwa.Text + " do bazy danych", "Dodano produkt");
}
/* command.CommandText = sql;
command.Connection = db;
command.Parameters.Add(new SqliteParameter("#name", Nazwa.Text));
command.Parameters.Add(new SqliteParameter("#RFID", RFID.Text));
command.Parameters.Add(new SqliteParameter("#price", Cena.Text));
command.Parameters.Add(new SqliteParameter("#unit", Jednostka.Text));
command.Parameters.Add(new SqliteParameter("#vat", VATcat));
command.ExecuteNonQuery();
MessageBox.Show("Pomyślnie dodano produkt " + Nazwa.Text + " do bazy danych", "Dodano produkt");
*/
}
}
}
}
db.Close();
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
I commented another way of adding to db (Will test both when I get rid of that exception)
Funny thing that if i change INSERT to SELECT it's working. If I use INSERT query directly in database file it's working too.

How to search over whole cities in combobox

I inserted about 18 cities in government field and I can search over each city I want by ID, but now I want to search over all of the cities by ID when I do not select any thing in combobox.
string c = "%";
c = comboBox1.Text;
int a;
a = Convert.ToInt32(textBox1.Text);
a = int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand("select * from Person where ( PER_ID = '" + a + "' and GOV_NAME_AR = '" + c + "') ", con);
cmd.CommandTimeout = 600;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
// MessageBox.Show("Successfully found Data");
// SqlDataReader DR = cmd.ExecuteReader();
BindingSource source = new BindingSource();
dataGridView1.DataSource = source;
}
else
{
MessageBox.Show("data not found");
}
con.Close();
You could change the statement in case of "nothing selected"
if (ComboBox.Text == string.Empty)
{
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
Remarks:
use variable names like string sCity = "%"; instead of string c = "%";
use parameters for your sql statements where ( PER_ID = #Person) and cmd.Parameters.Add("#Person", SqlDbType.Int32).Value = int.Parse(textBox1.Text);
If I get you correctly, you don't want where clause on GOV_NAME_AR when combobox1 is not selected.
if( ComboBox.SelectedItem == null ) {
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
You could do a check on the ComboBox.SelectedText like this:
if (comboBox1.SelectedText=="")
{
//SQL statement should not restrict on the c value
}
else
{
//Use your regular SQL query here.
}

I am getting {collection was modified after the enumerator was instantiated} this exception while closing the Form

my code is like this:
public partial class TimeTableForm : Form
{
string text;
string t;
string day;
public TimeTableForm(string str, string element,string d)
{
InitializeComponent();
text = str;
t = element;
day = d;
}
private void TimeTableForm_FormClosing(object sender, FormClosingEventArgs e)
{
//timetableData.Dispose();
//this.Visible = false;
this.Dispose();
Application.Exit();
//SelectElementForm ob = new SelectElementForm();
//ob.Show();
//this.Close();
}
//to generate the time table
public void GenerateTimeTable()
{
if(t == "Classes")
{
LogFile file = new LogFile();
file.LoggingInfo("Class selected: "+text+" and day selected: "+day);
SqlConnection conn = new SqlConnection("Data Source=WONDERBIZ;Initial Catalog=School_TimeTable;Integrated Security=True");
conn.Open();
string query = "select p.periodTime,s.subjectName,tc.teacherName,cr.classRomId from tbl_timetable t"
+" join tbl_Days d on d.dayId = t.dayId"
+" join tbl_Periods p on p.periodId = t.periodId"
+" join tbl_Subjects s on s.subjectId = t.subjectId"
+" join tbl_teachers tc on tc.teacherId = t.teacherId"
+" join tbl_classes cl on cl.classId = t.classId"
+" join tbl_classrooms cr on cr.classRomId = t.classroomId"
+" where cl.className = '"+text+"'"
+" and d.dayName = '"+day+"'"
+" order by p.periodId asc;";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//filling up the dataset
da.Fill(ds, "timetable data");
//showing the data
timetableData.DataSource = ds;
timetableData.DataMember = "timetable data";
conn.Close();
//ds.Clear();
}
catch(SqlException ex)
{
file.LoggingError(t + " timetable:" + ex.Message);
}
catch(Exception ex)
{
file.LoggingError(t+" timetable:" + ex);
}
ElementLabel.Text = "Class:";
SelectedElementLabel.Text = text;
dayLabel.Text = day;
}
if (t == "Teachers")
{
LogFile file = new LogFile();
file.LoggingInfo("Teacher selected: " + text + " and day selected: " + day);
SqlConnection conn = new SqlConnection("Data Source=WONDERBIZ;Initial Catalog=School_TimeTable;Integrated Security=True");
conn.Open();
string query = "select cl.className,p.periodTime,s.subjectName,cr.classRomId from tbl_timetable t"
+ " join tbl_Days d on d.dayId = t.dayId"
+ " join tbl_Periods p on p.periodId = t.periodId"
+ " join tbl_Subjects s on s.subjectId = t.subjectId"
+ " join tbl_teachers tc on tc.teacherId = t.teacherId"
+ " join tbl_classes cl on cl.classId = t.classId"
+ " join tbl_classrooms cr on cr.classRomId = t.classroomId"
+ " where tc.teacherName = '" + text + "'"
+ " and d.dayName = '" + day + "'"
+ " order by p.periodId asc;";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//filling up the dataset
da.Fill(ds, "timetable data");
//showing the data
timetableData.DataSource = ds;
timetableData.DataMember = "timetable data";
conn.Close();
}
catch (SqlException ex)
{
file.LoggingError(t + " timetable:" + ex.Message);
}
catch (Exception ex)
{
file.LoggingError(t + " timetable:" + ex);
}
ElementLabel.Text = "Teacher:";
SelectedElementLabel.Text = text;
dayLabel.Text = day;
}
if (t == "Classrooms")
{
LogFile file = new LogFile();
file.LoggingInfo("Classroom selected: " + text + " and day selected: " + day);
SqlConnection conn = new SqlConnection("Data Source=WONDERBIZ;Initial Catalog=School_TimeTable;Integrated Security=True");
conn.Open();
string query = "select cl.className,p.periodTime,s.subjectName,tc.teacherName from tbl_timetable t"
+ " join tbl_Days d on d.dayId = t.dayId"
+ " join tbl_Periods p on p.periodId = t.periodId"
+ " join tbl_Subjects s on s.subjectId = t.subjectId"
+ " join tbl_teachers tc on tc.teacherId = t.teacherId"
+ " join tbl_classes cl on cl.classId = t.classId"
+ " join tbl_classrooms cr on cr.classRomId = t.classroomId"
+ " where cr.classRomId = '" + text + "'"
+ " and d.dayName = '" + day + "'"
+ " order by p.periodId asc;";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//filling up the dataset
da.Fill(ds, "timetable data");
//showing the data
timetableData.DataSource = ds;
timetableData.DataMember = "timetable data";
conn.Close();
}
catch (SqlException ex)
{
file.LoggingError(t + " timetable:" + ex.Message);
}
catch (Exception ex)
{
file.LoggingError(t + " timetable:" + ex);
}
ElementLabel.Text = "Classroom:";
SelectedElementLabel.Text = text;
dayLabel.Text = day;
}
}
private void TimeTableForm_Load(object sender, EventArgs e)
{
GenerateTimeTable();
}

When i click the update button to update database values in SQL C# All Rows Are Affected by the same value

This is my screen shot
Bellow Is My Code For Update Button Click Event!
{
try
{
con = new SqlConnection(cs.ConDB);
con.Open();
string cb = "Update tblFees set Salutation= '" + cmbSalutation.Text + "' , Name= '" + tbName.Text + "',Sex = '" + cmbSex.Text + "', Date ='" + Date.Text + "',Fees_Amount='" + cmbFeesAmount.Text + "',Fees_Status='" + radioButton1.Checked + "'";
cmd = new SqlCommand(cb);
cmd.Connection = con;
cmd.ExecuteReader();
con.Close();
MessageBox.Show("Successfully updated", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
btnUpdate.Enabled = false;
btnSave.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
try
{
con = new SqlConnection(cs.ConDB);
con.Open();
cmd = new SqlCommand("SELECT * From tblFees", con);
SqlDataAdapter myDA = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
myDA.Fill(myDataSet, "tblFees");
dataGridView1.DataSource = myDataSet.Tables["tblFees"].DefaultView;
con.Close();
}catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);}`
Please Solve my problem i am new in the programming world
any help would be greatly appreciated
you should specify the rows using where condition
For example you can modify your query something like the following. I assume cboUser is a combo box there you can select particular user, so that the data updated for that selected user only.
SqlConnection con = new SqlConnection();
con.Open();
string cb = "Update [tblFees] set Salutation=#Salutation, Name=#Name,Sex =#Sex where tblFeesPK=#pk'";
SqlCommand cmd = new SqlCommand(cb, con);
cmd.Parameters.AddWithValue("#Salutation", cmbSalutation.Text);
cmd.Parameters.AddWithValue("#Name", tbName.Text);
cmd.Parameters.AddWithValue("#Sex", cmbSex.Text);
cmd.Parameters.AddWithValue("#pk", cboUser.SelectedValue);
cmd.ExecuteNonQuery();
If you want to update details based on name means: you can give name
in where condition. but it's not a proper way. so use primary
key(since name may have duplicate values)
You need to change the statement as:
string cb = "Update tblFees set Salutation= '" + cmbSalutation.Text + "' , Name= '" + tbName.Text + "',Sex = '" + cmbSex.Text + "', Date ='" + Date.Text + "',Fees_Amount='" + cmbFeesAmount.Text + "',Fees_Status='" + radioButton1.Checked + "' where Name= '" + tbName.Text + "'";
You need to add where Name= '" + tbName.Text + "';
Now it will update those rows where Name matches
Also as un-lucky said u should use parameterized queries

Categories

Resources