how to make database in C# - 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

Related

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

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)

C# Save file dialog box error

I created a simple project for parking car. When i register any user and save it in access database.After saving Dialog box is shown and ask me to save that user but problem when Dialog Box is shown error comes out about access violation exception.Read or write protected memory i don't know how to fix.
I read some blogs and posts about this error but no provide a correct solution and also not post any correct idea.
Below is my complete code how can i fix.
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.Configuration;
using System.Data.OleDb;
using MessagingToolkit.QRCode.Codec;
using MessagingToolkit.QRCode.Codec.Data;
using System.IO;
using NPR.Properties;
namespace NPR
{
public partial class UserAdd : Form
{
public UserAdd()
{
InitializeComponent();
}
private int userId = 0;
public int UserId
{
get { return userId; }
set { userId = value; }
}
private bool isUpdate = false;
public bool IsUpdate
{
get { return isUpdate; }
set { isUpdate = value; }
}
private void UpdateRecord()
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "Update users SET u_name = #name,u_car_no = #car_no, u_mobile_no = #mobile_no,u_license_no = #license_no,u_reg_date = #reg_date , u_image=#firstimage,u_car_background=#secondimage WHERE Id = #userId";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#name", NameTextBox.Text);
cmd.Parameters.AddWithValue("#car_no", PlateNoTextBox.Text);
cmd.Parameters.AddWithValue("#mobile_no", MobileTextBox.Text);
cmd.Parameters.AddWithValue("#license_no", LicenseTextBox.Text);
cmd.Parameters.AddWithValue("#reg_date", DateTime.Text);
cmd.Parameters.AddWithValue("#firstimage", savePhoto());
cmd.Parameters.AddWithValue("#secondimage", savePhoto2());
cmd.Parameters.AddWithValue("#userId", this.userId);
cmd.ExecuteNonQuery();
}
}
}
private void SaveRecord()
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "INSERT INTO users (u_name,u_car_no,u_mobile_no,u_license_no,u_reg_date,u_image,u_car_background) VALUES (#name,#car_no,#mobile_no,#license_no,#reg_date,#firstimage,#secondimage)";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#name", NameTextBox.Text);
cmd.Parameters.AddWithValue("#car_no", PlateNoTextBox.Text);
cmd.Parameters.AddWithValue("#mobile_no", MobileTextBox.Text);
cmd.Parameters.AddWithValue("#license_no", LicenseTextBox.Text);
cmd.Parameters.AddWithValue("#reg_date", DateTime.Text);
cmd.Parameters.AddWithValue("#firstimage", savePhoto());
cmd.Parameters.AddWithValue("#secondimage", savePhoto2());
cmd.ExecuteNonQuery();
}
}
}
private byte[] savePhoto()
{
MemoryStream ms = new MemoryStream();
FirstpictureBox.Image.Save(ms, FirstpictureBox.Image.RawFormat);
return ms.GetBuffer();
}
private byte[] savePhoto2()
{
MemoryStream ms = new MemoryStream();
SecondpictureBox.Image.Save(ms, SecondpictureBox.Image.RawFormat);
return ms.GetBuffer();
}
private bool IsValidated()
{
if (NameTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Name is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
NameTextBox.Focus();
return false;
}
if (PlateNoTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Car Plate No. is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
PlateNoTextBox.Focus();
return false;
}
if (MobileTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Mobile No. is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
MobileTextBox.Focus();
return false;
}
if (LicenseTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("License No. is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
NameTextBox.Focus();
return false;
}
if (DateTime.Text.Trim() == string.Empty)
{
MessageBox.Show("Date is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
DateTime.Focus();
return false;
}
return true;
}
private DataTable GetUserInfoById()
{
DataTable dtUsersInfo = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "SELECT * FROM users WHERE Id = #UserId";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#UserId", this.UserId);
OleDbDataReader reader = cmd.ExecuteReader();
dtUsersInfo.Load(reader);
}
}
return dtUsersInfo;
}
private Image LoadImg(byte[] img)
{
MemoryStream ms = new MemoryStream(img);
return Image.FromStream(ms);
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void SecondpictureBox_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select Car Background Image";
ofd.Filter = "Image File(*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";
if (ofd.ShowDialog() == DialogResult.OK)
{
SecondpictureBox.Image = new Bitmap(ofd.FileName);
}
}
private void FirstpictureBox_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select User Profile Image";
ofd.Filter = "Image File(*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";
if (ofd.ShowDialog() == DialogResult.OK)
{
FirstpictureBox.Image = new Bitmap(ofd.FileName);
}
}
private void button3_Click(object sender, EventArgs e)
{
DataTable dtUsers = GetUserInfoById();
DataRow row = dtUsers.Rows[0];
PlateNoTextBox.Text = row["u_car_no"].ToString();
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "DELETE * FROM users WHERE Id = #UserId";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#UserId", this.UserId);
cmd.ExecuteNonQuery();
}
}
string connString2 = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string camdString = "Update slots SET u_name = #name,u_car_no = #car_no,Status = 0 WHERE u_car_no = #slotId";
using (OleDbConnection conn = new OleDbConnection(connString2))
{
using (OleDbCommand cmd = new OleDbCommand(camdString, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#name", " ");
cmd.Parameters.AddWithValue("#car_no", " ");
cmd.Parameters.AddWithValue("#slotId", row["u_car_no"]);
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
MessageBox.Show("User Deleted Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
private void viewDataToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Hide();
AllUserDetail mef = new AllUserDetail();
mef.ShowDialog();
}
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Hide();
Dashboard dsh = new Dashboard();
dsh.ShowDialog();
}
private void UserAdd_Load(object sender, EventArgs e)
{
if (this.IsUpdate)
{
DataTable dtUsers = GetUserInfoById();
DataRow row = dtUsers.Rows[0];
NameTextBox.Text = row["u_name"].ToString();
PlateNoTextBox.Text = row["u_car_no"].ToString();
MobileTextBox.Text = row["u_mobile_no"].ToString();
LicenseTextBox.Text = row["u_license_no"].ToString();
DateTime.Text = row["u_reg_date"].ToString();
FirstpictureBox.Image = (row["u_image"] is DBNull) ? Resources.no_thumb : LoadImg((byte[])row["u_image"]);
SecondpictureBox.Image = (row["u_car_background"] is DBNull) ? Resources.no_thumb : LoadImg((byte[])row["u_car_background"]);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (IsValidated())
{
try
{
if (this.isUpdate)
{
UpdateRecord();
String plate = PlateNoTextBox.Text;
QRCodeEncoder encoder = new QRCodeEncoder();
Bitmap qrcode = encoder.Encode(plate);
qrimage.Image = qrcode as Image;
MessageBox.Show("Record Updated Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
SaveFileDialog s = new SaveFileDialog();
s.Title = "Save QR Code";
s.Filter = "JPEG|*.jpg|PNG|*.png|BMP|*.bmp|GIF|*.gif";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
qrimage.Image.Save(s.FileName);
}
catch (ApplicationException ex)
{
MessageBox.Show("ERROR:" + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
else
{
SaveRecord();
String plate = PlateNoTextBox.Text;
QRCodeEncoder encoder = new QRCodeEncoder();
Bitmap qrcode = encoder.Encode(plate);
qrimage.Image = qrcode as Image;
MessageBox.Show("Record Save Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
SaveFileDialog s = new SaveFileDialog();
s.Title = "Save QR Code";
s.Filter = "JPEG|*.jpg|PNG|*.png|BMP|*.bmp|GIF|*.gif";
if (s.ShowDialog() == DialogResult.OK)
{
try
{
qrimage.Image.Save(s.FileName);
}
catch (ApplicationException ex)
{
MessageBox.Show("ERROR:" + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
this.Close();
}
catch (ApplicationException ex)
{
MessageBox.Show("ERROR:" + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
Problem i face it in SaveRecord(); function dialog box.
if (s.ShowDialog() == DialogResult.OK) //Here is error
{
try
{
qrimage.Image.Save(s.FileName);
}
Please try to add s.InitialDirectory = "D:\\"; to prevent access to special directories when dialog opens

My Update Command Not Working To Update Database From DataGridView C#

Here is my code to update the database from datagridview if any body have the answer please tell me.
try
{
if (string.IsNullOrEmpty(tbName.Text) || string.IsNullOrEmpty(cmbSex.Text) || string.IsNullOrEmpty(cmbFeesAmount.Text) || string.IsNullOrEmpty(cmbFeesStatus.Text) || string.IsNullOrEmpty(cmbSex.Text) || string.IsNullOrEmpty(Date.Text)) { MessageBox.Show("Please Input data."); return; }
Update(lblDI.Text);
Reset();
this.BindGrid();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I Done some edits to the code and now it's working fine for me . i forgot to declare the sda.DeleteCommand = cb.GetDeleteCommand();
private static void CurdOperation()
{
SqlCeConnection con = new SqlCeConnection("Data Source="
+ System.IO.Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "MyDB.sdf"));
sda = new SqlCeDataAdapter();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from tblFees";
sda.SelectCommand = cmd;
SqlCeCommandBuilder cb = new SqlCeCommandBuilder(sda);
sda.InsertCommand = cb.GetInsertCommand();
sda.UpdateCommand = cb.GetUpdateCommand();
sda.DeleteCommand = cb.GetDeleteCommand();
}
#endregion
try
{
if (string.IsNullOrEmpty(tbName.Text) || string.IsNullOrEmpty(cmbSex.Text) || string.IsNullOrEmpty(cmbFeesAmount.Text) || string.IsNullOrEmpty(cmbFeesStatus.Text) || string.IsNullOrEmpty(cmbSex.Text) || string.IsNullOrEmpty(Date.Text)) { MessageBox.Show("Please Input data."); return; }
Update(lblDI.Text);
Reset();
this.BindGrid();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Now it Works.

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.

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