Getting an errors after change the files name - c#

I getting an several errors after i change the files name. From default form name (Form2.cs), (Form1.cs) etc to the System.cs, LoginPage.cs and while i change back to the default form name (Form2.cs), this is what happens, the errors appears. What should i do? Is there any solution that i can back this problem to the time before i changed the files name?
This is the full code of "Form1.cs":
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.Globalization;
using System.Data.OleDb;
using System.Security.Principal;
namespace Sell_System
{
public partial class Form1 : Form
{
string connectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\Archives\Projects\Program\Sell System\Sell System\App_Data\db1.accdb;Persist Security Info=False;");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label4.Visible = false;
comboBox1.Items.Add("English");
comboBox1.Items.Add("Indonesian");
comboBox1.SelectedIndex = 0;
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT DISTINCT [Username] FROM [Member]", conn);
dReader = cmd.ExecuteReader();
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
while (dReader.Read())
{
namesCollection.Add(dReader.GetString(0));
}
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
textBox1.AutoCompleteCustomSource = namesCollection;
dReader.Close();
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
DataTable dt = new DataTable();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Member] WHERE [Username]='" + textBox1.Text + "'AND [Password]='" + textBox2.Text + "'", conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows.Count != 0)
{
this.Hide();
Form2 secondaryForm = new Form2(this);
secondaryForm.ShowDialog();
this.Close();
}
else if (textBox1.Text == "Admin" && textBox2.Text == "")
{
this.Hide();
Form5 fifthForm = new Form5();
fifthForm.ShowDialog();
this.Close();
}
else
{
label4.Visible = true;
if (comboBox1.SelectedItem.ToString() == "English")
{
RecursiveClearTextBoxes(this.Controls);
label4.Text = "Invalid Username or Password!";
label4.ForeColor = Form1.Drawing.Color.Red;
}
else if (comboBox1.SelectedItem.ToString() == "Indonesian")
{
RecursiveClearTextBoxes(this.Controls);
label4.Text = "Username atau Password anda salah!";
label4.ForeColor = Form1.Drawing.Color.Red;
}
}
conn.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "English")
{
ChangeLanguage("en");
}
else if (comboBox1.SelectedItem.ToString() == "Indonesian")
{
ChangeLanguage("id");
}
}
private void ChangeLanguage(string language)
{
foreach (Control c in this.Controls)
{
ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1));
resources.ApplyResources(c, c.Name, new CultureInfo(language));
}
}
private void RecursiveClearTextBoxes(Control.ControlCollection cc)
{
foreach (Control ctrl in cc)
{
TextBox tb = ctrl as TextBox;
if (tb != null)
{
tb.Clear();
}
else
{
RecursiveClearTextBoxes(ctrl.Controls);
}
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
Form3 thirdForm = new Form3();
thirdForm.ShowDialog();
this.Close();
}
protected virtual void ClosedHandler(object sender, EventArgs e)
{
FormsHandler.Remove(this);
}
}
}
The error on "Form1.cs" is:
"Sell_System.Form1.cs" does not contain a definition for "Drawing"

Try to take a look at the designer class (designer.cs), maybe the designer class is still referencing the old file name?

Related

The connection was not closed. The connection's current state is open.C#

I am practicing my C# programming skill, I am relatively new, I am trying to create a software that helps my father to keep track with his document, I am doing quite well but run into this problem.
When i run the code, it works fine, and when I input some information to my textbox, let's say I input 123 as the ID, and it shows "Since this is already a primary key, and the ID already existed, choose something else", so I retype my ID as 1234 for testing purposes, and I got this error "The connection was not closed. The connection's current state is open" I do have con.Open() and con.Close(), but I still can not fix the problem, here is my code, if anyone can help, thank you so much:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Documents
{
public partial class hoadonKT : Form
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.HoaDonKetThucConnection);
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
public hoadonKT()
{
InitializeComponent();
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Label1_Click_1(object sender, EventArgs e)
{
}
private void Button1_Click(object sender, EventArgs e)
{
// save button
if (textBox1.Text == "" && textBox2.Text == "")
{
MessageBox.Show("Hay dien du thong tin can thiet");
}
else
{
try
{
con.Open();
cmd = new SqlCommand(#"INSERT INTO [dbo].[KTHoaDon]
([MaDon],[TenDon])
VALUES
('"+textBox1.Text+"','"+textBox2.Text+"')",con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Du Lieu Da Duoc Luu Tru");
fillGrid();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public void fillGrid()
{
// fill datagridview from datatable
con.Open();
da = new SqlDataAdapter("select * from KTHoaDon order by MaDon asc", con);
con.Close();
SqlCommandBuilder cd = new SqlCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
private void Button1_Click_1(object sender, EventArgs e)
{
}
private void HoadonKT_Load(object sender, EventArgs e)
{
fillGrid();
}
int i;
private void DataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
i = e.RowIndex;
DataGridViewRow row = dataGridView1.Rows[i];
textBox1.Text = row.Cells[0].Value.ToString();
textBox2.Text = row.Cells[1].Value.ToString();
}
}
}
try this code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Documents
{
public partial class hoadonKT : Form
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.HoaDonKetThucConnection);
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
public hoadonKT()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
// save button
if (textBox1.Text == "" && textBox2.Text == "")
{
MessageBox.Show("Hay dien du thong tin can thiet");
}
else
{
try
{
string queryText = "INSERT INTO [dbo].[KTHoaDon] ([MaDon],[TenDon]) VALUES(#MaDon,#TenDon)";
using (cmd = new SqlCommand(queryText, con))
{
cmd.Parameters.AddWithValue("MaDon", textBox1.Text);
cmd.Parameters.AddWithValue("TenDon", textBox2.Text);
cmd.ExecuteNonQuery();
}
MessageBox.Show("Du Lieu Da Duoc Luu Tru");
fillGrid();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public void fillGrid()
{
dt = new DataTable();
// fill datagridview from datatable
using (da = new SqlDataAdapter("select * from KTHoaDon order by MaDon asc", con))
{
da.Fill(dt);
}
dataGridView1.DataSource = dt;
}
private void HoadonKT_Load(object sender, EventArgs e)
{
con.Open();
fillGrid();
}
private void HoadonKT_FormClosing(object sender, FormClosingEventArgs e)
{
con.Close();
}
int i;
private void DataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
i = e.RowIndex;
DataGridViewRow row = dataGridView1.Rows[i];
textBox1.Text = row.Cells[0].Value.ToString();
textBox2.Text = row.Cells[1].Value.ToString();
}
}
}

Use one button for both save and edit on Gridview in c#

I have a scenario where I can save the name and phone number. but now I want to use my "Save" button as update button from clicking on grid view data.
Also after clicking on gridview data "save" button automatically change as "Update"
I want to know if there is any event or something to make it.
Screenshot of my form:
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace StoredProcedureExample
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection("Data Source=DESKTOP-S80LS9D;Initial Catalog=ComboBoxTest;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter data;
DataSet ds;
int num = 0;
int i;
public Form1()
{
InitializeComponent();
cmd = new SqlCommand("UserInformation", conn);
data = new SqlDataAdapter(cmd);
ds = new DataSet();
data.Fill(ds);
this.userdataGridView1.DataSource = ds.Tables[0];
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveRecord();
ShowRecordAfterSaveAndEdit();
clearfilds();
}
public void SaveRecord()
{
cmd = new SqlCommand("insertupdate", conn);
cmd.CommandType = CommandType.StoredProcedure;
if (userTextBox.Text == "")
{
num = 0;
}
else
{
num = int.Parse(userTextBox.Text);
}
cmd.Parameters.AddWithValue("#id", num);
cmd.Parameters.AddWithValue("#name", nameTextBox.Text);
cmd.Parameters.AddWithValue("#PhoneNumber", phoneNumberTextBox.Text);
if (saveButton.Text == "Save")
{
cmd.Parameters.AddWithValue("#Flag", 'S');
}
else
{
cmd = new SqlCommand("UpdateUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
}
try
{
conn.Open();
if (cmd.ExecuteNonQuery() > 0 && saveButton.Text == "Save")
{
MessageBox.Show("record inserted");
}
else
{
MessageBox.Show("record Update");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
public void clearfilds()
{
userTextBox.Text = "";
nameTextBox.Text = "";
phoneNumberTextBox.Text = "";
saveButton.Text = "Save";
}
public void ShowRecordAfterSaveAndEdit()
{
cmd = new SqlCommand("UserInformation", conn);
data = new SqlDataAdapter(cmd);
ds = new DataSet();
data.Fill(ds);
this.userdataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
private void ShowData(object sender, EventArgs e)
{
int show = userdataGridView1.CurrentRow.Index;
userTextBox.Text = userdataGridView1.CurrentRow.Cells["Id"].Value.ToString();
nameTextBox.Text = userdataGridView1.CurrentRow.Cells["Name"].Value.ToString();
phoneNumberTextBox.Text = userdataGridView1.CurrentRow.Cells["PhoneNumber"].Value.ToString();
}
}
}
Or you can create an Update button then place it behind the Save button. Add a RowHeaderMouseClick event on your dataGridView that will place the values from the highlighted cells to the textboxes.
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
//assuming the datagrid displays ID in the 1st cell, Cells[0]
string name = row.Cells[1].Value.ToString();
string phoneNum = row.Cells[2].Value.ToString();
}
textBox2.Text = name;
textBox3.Text = phoneNum;
updateButton.BringToFront();
saveButton.SendToBack(); //optional
}
Then, add these lines to your Update button Click event to bring the Save button in front again.
saveButton.BringToFront();
updateButton.SendToBack();
Make two Event for grid view.
1)Got Focus
2)Lost Focus
1)On GotFocus Event Change it to Update and maintain mode to insert and update
2)On Lost Focus Change it to Save.

Update/Delete buttons inside DataGridView not working after filtering results

C# winform application: i added buttons in datagridview in every row for (update,delete). it works fine but when i search data in this gridview the buttons doesn't work on search results.
Here is my code.
namespace MyBusiness
{
public partial class ExpenceDetails : Form
{
public ExpenceDetails()
{
InitializeComponent();
}
private void ExpenceDetails_Load(object sender, EventArgs e)
{
update();
}
DataTable data;
public void update()
{
string connectionstring = null;
SqlConnection cnn;
connectionstring = #"Server=(local)\SQLEXPRESS;Database=mrtraders;Trusted_Connection=True";
cnn = new SqlConnection(connectionstring);
try
{
cnn.Open();
dataGridView1.ColumnCount = 0;
SqlCommand cmd1 = new SqlCommand("SELECT * FROM Expense", cnn);
SqlDataReader reader = cmd1.ExecuteReader();
if (reader.HasRows)
{
data = new DataTable();
data.Load(reader);
dataGridView1.DataSource = data;
}
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
btn.Text = "Update";
btn.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(btn);
DataGridViewButtonColumn btn2 = new DataGridViewButtonColumn();
btn2.Text = "Delete";
btn2.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(btn2);
cnn.Close();
}
catch (Exception)
{
myMessageBox my = new myMessageBox("Internal Error...");
my.ShowDialog();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
this.Close();
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 4)
{
if (e.RowIndex >= 0)
{
//// get ExpenseId//// IMP
int id = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value);
string desc = Convert.ToString(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value);
int am = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[3].Value);
UpdateExpense a = new UpdateExpense(id,desc,am);
a.ShowDialog();
dataGridView1.DataSource = null;
update();
}
}
else if (e.ColumnIndex == 5)
{
if(e.RowIndex >= 0)
{
int id = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value);
string connectionstring = null;
SqlConnection cnn;
connectionstring = #"Server=(local)\SQLEXPRESS;Database=mrtraders;Trusted_Connection=True";
cnn = new SqlConnection(connectionstring);
try
{
cnn.Open();
SqlCommand cmd1 = new SqlCommand("Delete FROM Expense where expenseId = '"+id+"' ", cnn);
cmd1.ExecuteNonQuery();
myMessageBox my = new myMessageBox("Deleted Successfully...");
my.ShowDialog();
dataGridView1.DataSource = null;
cnn.Close();
update();
}
catch (Exception)
{
myMessageBox my = new myMessageBox("Internal Error...");
my.ShowDialog();
}
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(data);
dv.RowFilter = string.Format("Description like '%{0}%'", textBox1.Text);
dataGridView1.DataSource = dv.Table;
}
}
}

Auto suggest on gridview when typing on textbox

Can anyone help me on how can I do auto suggest on gridview when typing on textbox. Almost 1 week I seek for the solution. I already check my select statement, it connect to my database. And now I do not know why that coding is not function. Please somebody help me. This is my current code:
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.Data.SqlClient;
using System.Drawing.Imaging;
using System.IO;
namespace EmployeeVerification
{
public partial class Form1 : Form
{
//Connection String
string cs = "Server=..;User Id=sa;Password=..;Database=..";
SqlConnection con;
SqlDataAdapter adapt;
DataTable dt;
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
//table to show in gridview
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select [name], [empno], [workno] from [GMT].[dbo].[m_employee] where not [recsts] = 'R' order by empno", con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
//make the textbox read only
textBoxICPass.ReadOnly = true;
textBoxPassport.ReadOnly = true;
textBoxDept.ReadOnly = true;
textBoxSection.ReadOnly = true;
pictureBox1.Visible = false;
dataGridView1.Visible = false;
textBoxEmplNo.CharacterCasing = CharacterCasing.Upper;
textBoxWorkNo.CharacterCasing = CharacterCasing.Upper;
textBoxName.CharacterCasing = CharacterCasing.Upper;
DataGridViewColumn column = dataGridView1.Columns[0];
column.Width = 300;
}
//auto suggest on gridview when typing on textbox
private void textBoxName_TextChanged(object sender, EventArgs e)
{
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select [name], [empno], [workno] from m_employee where name like '%" + textBoxName.Text + "%' and not [recsts] = 'R' order by empno", con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
if (textBoxName.Text != null)
{
dataGridView1.Visible = true;
}
}
private void labelEmplNo_Click(object sender, EventArgs e)
{
}
private void textBoxEmplNo_TextChanged(object sender, EventArgs e)
{
}
private void textBoxWorkNo_TextChanged(object sender, EventArgs e)
{
}
private void labelTitle_Click(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void buttonSelect_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void textBoxICPass_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
}
//show the row value in textbox
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
textBoxName.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
textBoxEmplNo.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
textBoxWorkNo.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
textBoxICPass.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
textBoxPassport.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
textBoxDept.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
textBoxSection.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
dataGridView1.Visible = false;
}
//clear all the textbox fields after click
private void buttonClear_Click(object sender, EventArgs e)
{
foreach (Control crt in this.Controls)
{
if (crt.GetType() == typeof(TextBox))
crt.Text = "";
pictureBox1.Visible = false;
}
dataGridView1.Visible = false;
}
private void labelICPass_Click(object sender, EventArgs e)
{
}
private void textBoxWorkNo_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (textBoxWorkNo.Text != "")
{
//Do something
string selectSql = "select name, empno, icnum, passport, deptno, section from m_employee where workno=#workno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("#workno", textBoxWorkNo.Text);
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
textBoxEmplNo.Text = (read["empno"].ToString());
textBoxName.Text = (read["name"].ToString());
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
}
}
if(!isDataFound)
{
textBoxEmplNo.Text = "";
textBoxWorkNo.Text = "";
textBoxName.Text = "";
// Display message here that no values found
MessageBox.Show("No Result Found");
}
}
finally
{
con.Close();
}
}
else
{
textBoxEmplNo.Text = "";
textBoxName.Text = "";
}
string imgFilePath = #"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\photo\" + textBoxWorkNo.Text + ".jpg";
if (File.Exists(imgFilePath))
{
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(imgFilePath);
}
else
{
// Display message that No such image found
// MessageBox.Show("No Image Found");
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(#"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\photo\No-image-found.jpg");
}
}
}
private void textBoxEmplNo_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (textBoxEmplNo.Text != "")
{
string selectSql = "select name, workno, icnum, passport, deptno, section from m_employee where empno=#empno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("#empno", textBoxEmplNo.Text);
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
textBoxWorkNo.Text = (read["workno"].ToString());
textBoxName.Text = (read["name"].ToString());
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
}
}
if(!isDataFound)
{
textBoxEmplNo.Text = "";
textBoxWorkNo.Text = "";
textBoxName.Text = "";
// Display message here that no values found
MessageBox.Show("No Result Found");
}
}
finally
{
con.Close();
}
}
else
{
textBoxWorkNo.Text = "";
textBoxName.Text = "";
}
string imgFilePath = #"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\photo\" + textBoxEmplNo.Text + ".jpg";
if(File.Exists(imgFilePath))
{
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(imgFilePath);
}
else
{
// Display message that No such image found
MessageBox.Show("No Image Found");
}
}
}
}
}
Make these changes within your code:
You are setting dataGridView1.Visible = false; at various places within your code, remove all of them for instance, just for the sake of testing, you can add them later based on your requirements.
Remove this part of query where not [recsts] = 'R' order by empno" because for now it is useless and I don't understand why you are using this, you can apply filters later and also select ... from m_employee instead of [dbo]... etc..
Instead of dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); get data from selected row like this: textBoxName.Text = dataGridView1.Rows[e.RowIndex].Cells["name"].Value.ToString(); Because in future, if you increase/decrease the number of columns or re-arrange the order of getting data, it will not effect.
I've tested your code with these modifications and it works perfectly.

Date in ComboBox 2 always changed every time i change the ComboBox 1

i have 2 ComboBox (ComboBox 1 and ComboBox 2) in my program and i am having a problem, when i select a date "10/10/2014" in ComboBox 1, the ComboBox 2 is changed same exactly like i did in ComboBox 1, why is it like that?
Here is the code:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
private const int CP_NOCLOSE_BUTTON = 0x200;
private Choices _choice;
private DataSet _ds = new DataSet();
private List<DateTime> _dateTime = new List<DateTime>();
public Trans()
{
InitializeComponent();
}
public Trans(Choices _choice)
: this()
{
this._choice = _choice;
}
private void Trans_Load(object sender, EventArgs e)
{
for (int i = 0; i < DateTime.Today.AddYears(1).Subtract(DateTime.Today).TotalDays + 1; i++)
{
_dateTime.Add(DateTime.Today.AddDays(i));
}
ViewDatabase(sender, e);
StartDateCollection(sender, e);
EndDateCollection(sender, e);
this.dataGridView1.Columns["ID"].Visible = false;
this.dataGridView1.Sort(this.dataGridView1.Columns["Times"], System.ComponentModel.ListSortDirection.Ascending);
this.label3.Text = "Welcome, " + UserInformation.CurrentLoggedInUser + " " + " " + "-" + " " + " " + UserInformation.CurrentLoggedInUserType;
this.label3.ForeColor = System.Drawing.Color.White;
dataGridView1.RowPostPaint += new DataGridViewRowPostPaintEventHandler(this.SetRowNumber);
dataGridView1.ClearSelection();
}
private void ViewDatabase(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [ProductCode], [Quantity], [Description], [SubTotal], [Total], [IssuedBy], [To], [Dates], [Times] FROM [TransRecord]";
conn.Open();
using (OleDbDataAdapter _adapter = new OleDbDataAdapter(query, conn))
{
_ds.Clear();
_adapter.Fill(_ds, "TransRecord");
dataGridView1.DataSource = null;
dataGridView1.Refresh();
}
dataGridView1.DataSource = _ds.Tables[0];
conn.Close();
}
}
private void SetRowNumber(object sender, DataGridViewRowPostPaintEventArgs e)
{
var grid = sender as DataGridView;
var rowIdx = (e.RowIndex + 1).ToString();
var centerFormat = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}
private void StartDateCollection(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [Dates] FROM [TransRecord]";
conn.Open();
using (OleDbDataAdapter _adapter = new OleDbDataAdapter(query, conn))
{
comboBox1.DataSource = _dateTime;
comboBox1.FormatString = "M/dd/yyyy";
comboBox1.FormattingEnabled = true;
}
}
}
private void EndDateCollection(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [Dates] FROM [TransRecord]";
conn.Open();
using (OleDbDataAdapter _adapter = new OleDbDataAdapter(query, conn))
{
comboBox2.DataSource = _dateTime;
comboBox2.FormatString = "M/dd/yyyy";
comboBox2.FormattingEnabled = true;
}
}
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
QuitProgram(sender, e);
}
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
PrintFile(sender, e);
}
private void button1_Click(object sender, EventArgs e)
{
GetData(sender, e);
}
private void button2_Click(object sender, EventArgs e)
{
Clear(sender, e);
}
private void PrintFile(object sender, EventArgs e)
{
}
private void GetData(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [ProductCode], [Quantity], [Description], [SubTotal], [Total], [IssuedBy], [To], [Dates], [Times] FROM [TransRecord] WHERE [Dates] = #Dates ORDER BY [Dates]";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Dates", System.Data.OleDb.OleDbType.Date);
cmd.Parameters["#Dates"].Value = this.comboBox1.SelectedValue;
using (OleDbDataAdapter _adapter = new OleDbDataAdapter(cmd))
{
_ds.Clear();
_adapter.Fill(_ds, "TransRecord");
dataGridView1.DataSource = null;
dataGridView1.Refresh();
}
dataGridView1.DataSource = _ds.Tables[0];
conn.Close();
}
}
}
private void QuitProgram(object sender, EventArgs e)
{
if (_choice.comboBox1.Text == "English")
{
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("Are You Sure Want to Quit?", "Warning", MessageBoxButtons.YesNo);
if (_dialogResult == DialogResult.Yes)
{
this.Hide();
this.Close();
}
else
{
}
}
else if (_choice.comboBox1.Text == "Indonesian")
{
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("Apakah Kamu Benar-benar mau Keluar?", "Warning", MessageBoxButtons.YesNo);
if (_dialogResult == DialogResult.Yes)
{
this.Hide();
this.Close();
}
else
{
}
}
}
private void Clear(object sender, EventArgs e)
{
if (_choice.comboBox1.Text == "English")
{
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("Are You Sure Want to Clear all the Data?", "Warning", MessageBoxButtons.YesNo);
if (_dialogResult == DialogResult.Yes)
{
ClearDatabase(sender, e);
}
else
{
}
}
else if (_choice.comboBox1.Text == "Indonesian")
{
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("Apakah Kamu Yakin mau Menghapus semua Data?", "Warning", MessageBoxButtons.YesNo);
if (_dialogResult == DialogResult.Yes)
{
ClearDatabase(sender, e);
}
else
{
}
}
}
private void ClearDatabase(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "DELETE FROM [TransRecord]";
conn.Open();
using (OleDbDataAdapter _adapter = new OleDbDataAdapter(query, conn))
{
_ds.Clear();
_adapter.Fill(_ds, "TransRecord");
dataGridView1.DataSource = null;
dataGridView1.Refresh();
}
dataGridView1.DataSource = _ds.Tables[0];
conn.Close();
}
if (_choice.comboBox1.Text == "English")
{
System.Media.SoundPlayer _sounds = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
_sounds.Play();
MessageBox.Show("Cleared!", "Cleared");
}
else if (_choice.comboBox1.Text == "Indonesian")
{
System.Media.SoundPlayer _sounds = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
_sounds.Play();
MessageBox.Show("Berhasil Dibersihkan!", "Cleared");
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams myCp = base.CreateParams;
myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
return myCp;
}
}
}
Here is the screenshot:
in above picture, when the form load, the date in combobox 1 is 9/22/2013.
in above picture, i just wanted to change the date in combobox 1 to 9/24/2013, but it change the date in combobox 2 too.
How to fix it? Thanks
It's because you use the same DataSource _datetime for both comboboxes:
comboBox1.DataSource = _dateTime;
comboBox2.DataSource = _dateTime.ToList();
However I think _dateTime may be not what you want to set as DateSource for both the comboboxes, if it's the case, just leave some comment.

Categories