I'm having a problem with MySql in C# .Net Framework - c#

I'm migrating from Access to MySql. When "btn_Ekle" is clicked, the shelf is added to the database, but the codes written afterwards do not work.
Also, RafListesi() works at first, but when we close the Add Shelves window after adding a shelf and then open it again, the shelfs are not listed. It is listed after reopening the program.
public static ClassRaf RafEkle(string ad)
{
ClassRaf result;
try
{
if (ClassData.RafSec(ad) != null)
{
MessageBox.Show("Eklemek İstediğiniz Raf Zaten Kayıtlarda Mevcut.", "Kütüphane Sistemi | Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
result = null;
}
else
{
MySqlCommand sqlCommand = new MySqlCommand("INSERT INTO bookrack (shelf_name) VALUES (#shelf_name)", ClassData.connectSql);
sqlCommand.Parameters.Add("#shelf_name", MySqlDbType.VarChar).Value = ad;
if (sqlCommand.ExecuteNonQuery() > 0)
{
MySqlCommand sqlCommand1 = new MySqlCommand("SELECT * FROM bookrack ORDER BY id DESC", ClassData.connectSql);
MySqlDataReader sqlDataReader = sqlCommand1.ExecuteReader();
if (sqlDataReader.Read())
{
result = ClassData.RafSec((int)sqlDataReader["id"]);
}
else
{
result = null;
}
}
else
{
result = null;
}
}
}
catch
{ result = null; }
return result;
}
private void btnEkle_Click(object sender, EventArgs e)
{
ClassRaf classRaf = ClassData.RafEkle(txtEkle.Text);
if (classRaf != null)
{
txtEkle.Text = "";
liste.Items.Add(classRaf.Ad);
ClassLog.Log(string.Concat(new object[]
{
classRaf.Ad,
" adlı raf eklendi. ID=[",
classRaf.ID,
"]"
}));
ShelfValid();
txtEkle.Select();
}
}
public static List<ClassRaf> RafListesi()
{
List<ClassRaf> result;
try
{
List<ClassRaf> list = new List<ClassRaf>();
MySqlCommand sqlCommand = new MySqlCommand("SELECT * FROM bookrack", ClassData.connectSql);
MySqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
list.Add(new ClassRaf
{
ID = Convert.ToInt32(sqlDataReader["id"]),
Ad = sqlDataReader["shelf_name"].ToString()
});
}
result = list;
sqlDataReader.Close();
sqlDataReader.Dispose();
}
catch
{ result = new List<ClassRaf>(); }
return result;
}
public static ClassRaf RafEkle(string ad) - (Add Shelf)
private void btnEkle_Click
private void btnEkle_Click(object sender, EventArgs e)

Related

how to make database in C#

Here is my code:
private void btnSimpan_Click(object sender, EventArgs e)
{
Employees employees = new Employees();
employees.EmployeeNumber = txtEmployeeNumber.Text;
employees.LastName = txtLastName.Text;
employees.FirstName = txtFirstName.Text;
employees.Extension = txtExtension.Text;
employees.Email = txtEmail.Text;
employees.OfficeCode = cboOfficeCode.Text;
if (employees.OfficeCode.CompareTo("1") == 0 || employees.OfficeCode.CompareTo("2") == 0 || employees.OfficeCode.CompareTo("3") == 0) employees.ReportsTo = "1143";
else if (employees.OfficeCode.CompareTo("4") == 0 || employees.OfficeCode.CompareTo("5") == 0) employees.ReportsTo = "1102";
else employees.ReportsTo = "1088";
employees.JobTitle = "Sales Rep";
try
{
stringBuilder = new StringBuilder();
stringBuilder.Append(#"INSERT INTO employees (employeeNumber, lastName, firstName, extension, email, officeCode, reportsTo, jobTitle) VALUES (");
stringBuilder.Append(employees.EmployeeNumber);
stringBuilder.Append(", '");
stringBuilder.Append(employees.LastName);
stringBuilder.Append("', '");
stringBuilder.Append(employees.FirstName);
stringBuilder.Append("', '");
stringBuilder.Append(employees.Extension);
stringBuilder.Append("', '");
stringBuilder.Append(employees.Email);
stringBuilder.Append("', ");
stringBuilder.Append(employees.OfficeCode);
stringBuilder.Append(", '");
stringBuilder.Append(employees.ReportsTo);
stringBuilder.Append("', '");
stringBuilder.Append(employees.JobTitle);
stringBuilder.Append("')");
comm = new MySqlCommand();
comm.Connection = conn;
comm.CommandText = stringBuilder.ToString();
// Memakai ExecuteNonQuery, return n data yang terkena dampak
int jmlDataTertambah = comm.ExecuteNonQuery();
MessageBox.Show(jmlDataTertambah.ToString() + " data berhasil disimpan");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
this.Close();
}
}
public partial class frmMain : Form
{
MySqlConnection conn = null;
public frmMain()
{
InitializeComponent();
}
private void mnuConnect_Click(object sender, EventArgs e)
{
if (mnuConnect.Text.CompareTo("Connect") == 0)
{
String connString = #"Server=127.0.0.1;Database=product_sales_company;Uid=root;Pwd=;";
try
{
conn = new MySqlConnection(connString);
conn.Open(); // Membuka koneksi
mnuEmployee.Enabled = true;
mnuConnect.Text = "Disconnect";
lblStatusKoneksi.Text = "Connected";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
if (conn != null)
{
conn.Close(); // Menutup koneksi
conn.Dispose();
}
foreach (Form form in this.MdiChildren)
{
form.Close();
}
mnuEmployee.Enabled = false;
mnuConnect.Text = "Connect";
lblStatusKoneksi.Text = "Disconnected";
}
}
private void mnuExit_Click(object sender, EventArgs e)
{
if (conn != null)
{
conn.Close(); // Menutup koneksi
conn.Dispose();
}
Application.Exit();
}
private void mnuList_Click(object sender, EventArgs e)
{
// Cek apakah form yang memiliki jenis form yang sama (frmDaftarEmployee) sudah ada yang terbuka
foreach (Form form in this.MdiChildren)
{
if (form.GetType() == typeof(frmDaftarEmployee))
{
form.Activate(); // Membuat form yang ditunjuk menjadi aktif
return;
}
}
frmDaftarEmployee formDafarEmployee = new frmDaftarEmployee(conn);
formDafarEmployee.MdiParent = this;
formDafarEmployee.Show();
}
}
}
To create a database use Create command like this:
public void CreateDatabase(String createDb)
{
String connstr = ConfigurationManager.ConnectionStrings["Connstr"].ToString();
MySqlConnection cnn = new MySqlConnection(connstr);
try
{
cnn.Open();
object result = string.Empty;
MySqlCommand Command = new MySqlCommand();
Command = cnn.CreateCommand();
Command.CommandType = CommandType.Text;
Command.CommandText = createDb;
Command = new MySqlCommand(Query, cnn);
//result = (object)NpgCommand.ExecuteScalar();
Command.ExecuteNonQuery();
}
catch (Exception er)
{
String errorhere = er.Message;
if (cnn != null)
{
cnn.Close();
}
}
finally
{
if (cnn != null)
{
cnn.Close();
}
}
}
Then call the function on your form_load:
String createDb = "Create Database DBSample";
CreateDatabase(String createDb);
make sure you set the connection string at your app.config file.
It look like this:
<configuration>
<connectionStrings>
<add name="Connstr" connectionString="data source=localhost;initial catalog=dbname;user=usename;password=password; default command timeout=120" />
</connectionStrings>
</configuration>
good luck

code asp.net c# oledb, cookies, if else

Can somebody help understand this code?
protected void Page_Load(object sender, EventArgs e)
{
Database database = new Database();
OleDbConnection conn = database.connectDatabase();
if (Request.Cookies["BesteldeArtikelen"] == null)
{
lbl_leeg.Text = "Er zijn nog geen bestelde artikelen";
}
else
{
HttpCookie best = Request.Cookies["BesteldeArtikelen"];
int aantal_bestel = best.Values.AllKeys.Length;
int[] bestelde = new int[aantal_bestel];
int index = 0;
foreach (string art_id in best.Values.AllKeys)
{
int aantalbesteld = int.Parse(aantalVoorArtikel(int.Parse(art_id)));
int artikel_id = int.Parse(art_id); // moet getalletje zijn
if (aantalbesteld != 0)
{
bestelde[index] = artikel_id;
}
index++;
}
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT artikel_id, naam, prijs, vegetarische FROM artikel WHERE artikel_id IN (" +
String.Join(", ", bestelde) + ")";
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception error)
{
errorMessage.Text = error.ToString();
}
finally
{
conn.Close();
}
}
}
And there is this part of code i dont really understand:
public string aantalVoorArtikel(object id)
{
int artikel_id = (int)id;
if (Request.Cookies["BesteldeArtikelen"] != null &&
Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()] != null)
{
return Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()];
}
else
{
return "0";
}
}
It extracts values from a cookie and builds an int array. (Displays a message if the cookie value is null) The int array is then used as the value for the SQL IN operator when querying the database. The result set is then bound to the GridView.

The connection is open

A few months ago I made a test program for a project and everything worked fine there.
Now I am working on the program itself, so I copied the code from the test program and
changed the the names of the columns,buttons etc. so it would fit the current program.
When I try to add something into the database it does nothing on the first click, on the
second pops up an error which says that the connection is open.. I really got no idea what's
the problem. I tried to check again if I made a mistake in a column name or the database name
but everything seems to be correct.
Note: I also have a function that show data from the database and it works without any problem.
private void InsertData()
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
Connection.Open();
DataAdd.ExecuteNonQuery();
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
string NewRowNum()
{
string Row = RowFind();
int CalcRow = int.Parse(Row) + 1;
Row = CalcRow.ToString();
return Row;
}
The connection that appears to be open is the one in the string RowFind().
Here are the other related things to the database:
public partial class frmShop : Form
{
System.Data.SqlClient.SqlConnection Connection;
public frmShop()
{
string DatabaseConnection = WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1;
Connection = new System.Data.SqlClient.SqlConnection();
Connection.ConnectionString = DatabaseConnection;
InitializeComponent();
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
Connection.Open();
SqlDataReader ReadSentence = null;
Int32 BinaryInt = Int32.Parse(txtBinaryString.Text);
string CommandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
SqlCommand Command = new SqlCommand(CommandString, Connection);
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
ReadSentence = Command.ExecuteReader();
while (ReadSentence.Read())
{
txtSentence.Text = (ReadSentence["Sentence"].ToString());
Fit = 1;
}
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You are getting errors because you are reusing the same connection Connection.Open(); several times.
Your method InsertData() is doing this 3 times in the same method.
You should create a new instance of the connection object and dispose it on your methods.
Using Statement are the way to go.
private void InsertData()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
Connection.Open();
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
DataAdd.ExecuteNonQuery();
//Connection.Close(); no need to close
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You can save one more connection if you store the row returned by RowFind()
string RowFind()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
//Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
So you would connect once instead of twice:
var Row = RowFind();
string NewCode = GenerateCode(Row);
string NewRow = NewRowNum(Row);
string NewSentence = txtSentence.Text;
Declare your connection string variable to a property so you can reuse it:
private string DatabaseConnection {get; set;}
Instead using an instance level SqlConnection you should only provide a common factory for creating a connection:
public partial class frmShop : Form
{
private string ConnectionString
{
get { return WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1; }
}
public frmShop()
{
InitializeComponent();
}
private SqlConnection CreateConnection()
{
var conn = new SqlConnection(ConnectionString);
conn.Open();
return conn;
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
using (var conn = CreateConnection())
{
var BinaryInt = int.Parse(txtBinaryString.Text);
var commandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
using (var Command = new SqlCommand(commandString, conn))
{
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
using (var readSentence = Command.ExecuteReader())
{
while (readSentence.Read())
{
txtSentence.Text = (readSentence["Sentence"].ToString());
Fit = 1;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void InsertData()
{
try
{
using (var conn = CreateConnection())
{
var commandString = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
using (var comm = new SqlCommand(commandString, conn))
{
comm.Parameters.AddWithValue("#NewBinaryString", GenerateCode());
comm.Parameters.AddWithValue("#NewNewSentence", txtSentence.Text);
comm.Parameters.AddWithValue("#NewRowNumber", NewRowNum());
comm.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
using (var conn = CreateConnection())
{
var commandString = "SELECT * FROM ShopSentences";
using (var comm = new SqlCommand(commandString, conn))
{
using (var sda = new SqlDataAdapter(queryString, Connection))
{
using (DataTable dt = new DataTable("ShopSentences"))
{
sda.Fill(dt);
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
}
}
}
string NewRowNum()
{
var Row = RowFind();
var CalcRow = int.Parse(Row) + 1;
return CalcRow.ToString();
}
}
But this is just the beginning you should not have any hard SQL dependency in your Form classes.
When sharing same SqlConnection instance several times in your code, instead of directly opening the you can rather check the connection state first and then open it if not already opened. For example:
if(Connection.State!= ConnectionState.Open)
Connection.Open();

Why is this ignoring the where clause?

Why is the where clause being ignored in this code? It seems to be ignoring the where clause on the update which means every records has been written over. How can i fix this? Any help would be greatly appreciated.
namespace ResitAssignment2
{
public partial class HomeCareVisitEddit : Form
{
public HomeCareVisitEddit()
{
InitializeComponent();
}
private void SubmitHCVA_Click(object sender, EventArgs e)
{
SqlConnection a = Database.GetConnection();
a.Open();
string sqltext;
sqltext = #"update HomeCareVisit set
PatientNo=#PatientNo,
FurtherVisitRequired=#FurtherVisitRequired,
AdvisoryNotes=#AdvisoryNotes,
Prescription=#Prescription,
TreatmentProvided=#TreatmentProvided,
ActualVisitDateTime=#ActualVisitDateTime,
Priority=#Priority,
ScheduledDateTime=#ScheduledDateTime,
TreatmentInstructions=#TreatmentInstructions,
MedicalStaffID=#MedicalStaffID
WHERE
VisitRefNo=VisitRefNo";
SqlCommand command = new SqlCommand(sqltext, a);
try
{
using (a)
{
command.Parameters.AddWithValue("#PatientNo", PatientNo.Text);
command.Parameters.AddWithValue("#FurtherVisitRequired", FurtherVisitRequired.Text);
command.Parameters.AddWithValue("#AdvisoryNotes", AdvisoryNotes.Text);
command.Parameters.AddWithValue("#Prescription", Prescription.Text);
command.Parameters.AddWithValue("#TreatmentProvided", TreatmentProvided.Text);
command.Parameters.AddWithValue("#ActualVisitDateTime",SqlDbType.DateTime );
{
DateTime.Parse(ActualVisitDateTime.Text);
};
command.Parameters.AddWithValue("#Priority", Priority.Text);
command.Parameters.AddWithValue("#ScheduledDateTime",SqlDbType.DateTime );
{
DateTime.Parse(ScheduledDateTime.Text);
};
command.Parameters.AddWithValue("#TreatmentInstructions", TreatmentInstructions.Text);
command.Parameters.AddWithValue("#MedicalStaffID", MedicalStaffID.Text);
command.Parameters.AddWithValue("#VisitRefNo", VisitRefNo.Text);
command.ExecuteNonQuery();
MessageBox.Show("Record altered");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
a.Close();
}
private void HomeCareVisitEddit_Load(object sender, EventArgs e)
{
SqlConnection a = Database.GetConnection();
a.Open();
string sqlText = "select * from HomeCareVisit where VisitRefNo =" + VisitRefNo;
SqlCommand command = new SqlCommand(sqlText, a);
SqlDataReader HomeCareVisitData = command.ExecuteReader();
while (HomeCareVisitData.Read())
{
//DateTime actual = DateTime.Parse("ActualVisitDateTime");
//DateTime scheduled = DateTime.Parse("ActualVisitDateTieme");
PatientNo.Text = HomeCareVisitData["PatientNo"].ToString();
FurtherVisitRequired.Text = HomeCareVisitData["FurtherVisitRequired"].ToString();
AdvisoryNotes.Text = HomeCareVisitData["AdvisoryNotes"].ToString();
Prescription.Text = HomeCareVisitData["Prescription"].ToString();
TreatmentProvided.Text = HomeCareVisitData["TreatmentProvided"].ToString();
ActualVisitDateTime.Text = HomeCareVisitData["ActualVisitDateTime"].ToString();
Priority.Text = HomeCareVisitData["Priority"].ToString();
ScheduledDateTime.Text = HomeCareVisitData["ScheduledDateTime"].ToString();
TreatmentInstructions.Text = HomeCareVisitData["TreatmentInstructions"].ToString();
MedicalStaffID.Text = HomeCareVisitData["MedicalStaffID"].ToString();
}
a.Close();
}
}
}
WHERE VisitRefNo=VisitRefNo"; should be WHERE VisitRefNo=#VisitRefNo";.
WHERE VisitRefNo=VisitRefNo
Should be
WHERE VisitRefNo=#VisitRefNo

No mapping exists from object type System.Data.DataRowView to a known managed provider native type

i have a windows form in c# which has 3 comboboxes. now the problem is when i pass the sql query of insertion it gives me this error. please help me to solve the error. here is the code.
namespace login
{
public partial class samplerequisition : Form
{
SqlConnection con = new SqlConnection("Data Source=TH07L019;Initial Catalog=procurement1;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader rdr;
DataSet dsreqname = new DataSet();
DataSet dsprepname = new DataSet();
DataSet dsauthorizedname = new DataSet();
public samplerequisition()
{
InitializeComponent();
}
bool IsAllValid()
{
if (String.IsNullOrEmpty(txtreqno.Text))
{
return false;
}
else if (String.IsNullOrEmpty(txtexpectedate.Text))
{
return false;
}
else if (String.IsNullOrEmpty(txtcc.Text))
{
return false;
}
else if (String.IsNullOrEmpty(txtbrand.Text))
{
return false;
}
/*else if (String.IsNullOrEmpty(txtprepname.Text))
{
return false;
}
else if (String.IsNullOrEmpty(txtauthorizedname.Text))
{
return false;
}*/
else if (cmbrequisitionname.SelectedItem==null)
{
return false;
}
else if (cmbpreparedname.SelectedItem == null)
{
return false;
}
else if (cmbauthorizedname.SelectedItem == null)
{
return false;
}
else if (Convert.ToString(dtreqdate.Value) == "")
{
return false;
}
else if (Convert.ToString(dtprepdate.Value) == "")
{
return false;
}
else if (Convert.ToString(dtauthorizedate.Value) == "")
{
return false;
}
else
{
return true;
}
}
private void samplerequisition_Load(object sender, EventArgs e)
{
SqlDataAdapter adp = new SqlDataAdapter(cmd);
cmd.Connection = con;
cmd.CommandText = "select * from employee";
adp.Fill(dsreqname,"employee");
cmbrequisitionname.DataSource = dsreqname.Tables["employee"];
cmbrequisitionname.DisplayMember = "fname";
cmbrequisitionname.SelectedIndex = -1;
adp.Fill(dsprepname, "employees");
cmbpreparedname.DataSource = dsprepname.Tables["employees"];
cmbpreparedname.DisplayMember = "fname";
cmbpreparedname.SelectedIndex = -1;
adp.Fill(dsauthorizedname, "employees");
cmbauthorizedname.DataSource = dsauthorizedname.Tables["employees"];
cmbauthorizedname.DisplayMember = "fname";
cmbauthorizedname.SelectedIndex = -1;
}
private void btnsave_Click(object sender, EventArgs e)
{
con.Open();
if (IsAllValid())
{
cmd.CommandText = "insert into samplerequisition(req_no,reqemployee_id,charges,expected_date,reqdate,costcenter_id,specific_brand,preparedemployee_id,prepared_date,authorizedemployee_id,auhtorized_date) values(#req_no,#reqemployee_id,#expected_date,#reqdate,#charges,#costcenter_id,#specific_brand,#preparedemployee_id,#prepared_date,#authorizedemployee_id,#auhtorized_date)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#req_no",txtreqno.Text);
cmd.Parameters.AddWithValue("#reqemployee_id",cmbrequisitionname.SelectedValue);
cmd.Parameters.AddWithValue("#expected_date",txtexpectedate.Text );
cmd.Parameters.AddWithValue("#reqdate", dtreqdate.Value);
cmd.Parameters.AddWithValue("#costcenter_id",txtcc.Text);
cmd.Parameters.AddWithValue("#specific_brand",txtbrand.Text);
cmd.Parameters.AddWithValue("#preparedemployee_id",cmbpreparedname.SelectedValue);
cmd.Parameters.AddWithValue("#prepared_date", dtprepdate.Value);
cmd.Parameters.AddWithValue("#authorizedemployee_id",cmbauthorizedname.SelectedValue);
cmd.Parameters.AddWithValue("#auhtorized_date", dtauthorizedate.Value);
if (rdcapex.Checked)
{
cmd.Parameters.AddWithValue("#charges", "Capex");
}
else
{
cmd.Parameters.AddWithValue("#charges", "revenue");
}
cmd.ExecuteNonQuery();
MessageBox.Show("record saved","requisition",MessageBoxButtons.OKCancel,MessageBoxIcon.Information);
}
else
{
MessageBox.Show("error","requisition",MessageBoxButtons.OKCancel,MessageBoxIcon.Error);
con.Close();
}
}
}
}
You are never setting what "value" to use for your combo boxes. So, by default, comboboxName.SelectedValue returns the whole row instead of just one column of the row. If you just want one column of the row (I am assuming fname like the displayed value) then just add the following 3 lines to your code.
cmbrequisitionname.ValueMember = "fname";
cmbpreparedname.ValueMember = "fname";
cmbauthorizedname.ValueMember = fname";

Categories

Resources