Auto suggest on gridview when typing on textbox - c#

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.

Related

Displaying datetime on a chart's x axis and subsequently on a tooltip showing x and y axis value

namespace TRSQL
{
public partial class Form1 : Form
{
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
private ImageList imagelst;
public SqlDataReader dr1;
public Form1()
{
imagelst = new ImageList();
InitializeComponent();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = 1000;
}
private void timer_Tick(object sender, EventArgs e)
{
timer.Enabled = false;
button1.PerformClick();
}
private void button1_Click(object sender, EventArgs e)
{
chart1.Series["Series1"].Points.Clear();
SqlConnection con = new SqlConnection(#"server=HIST;database=PLC_DB;uid=sa;password=NCADMIN#123;MultipleActiveResultSets=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from [PLC_DB].[dbo].[EVEREST] WHERE DATESTR BETWEEN '" + dateTimePicker1.Value.ToString("yyyy/MM/dd ") + "' AND '" + dateTimePicker2.Value.ToString("yyyy/MM/dd") + "'", con);
cmd.ExecuteNonQuery();
dr1 = cmd.ExecuteReader();
while (dr1.Read())
{
chart1.Series["Series1"].Points.Clear();
chart1.Series["Series1"].Color = Color.Red;
chart1.Series["Series1"].Points.AddXY(dr1["DATESTR"].ToString(), dr1["Value"].ToString());
chart1.ChartAreas[0].AxisX.Enabled = System.Windows.Forms.DataVisualization.Charting.AxisEnabled.True;
chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
//chart1.Update();
////chart1.Series.IsValueShownAsLabel = true;
chart1.ChartAreas[0].AxisX.LabelStyle.Interval = 1;
chart1.Series["Series1"].IsValueShownAsLabel = true;
chart1.ChartAreas[0].AxisY.Maximum = 250;
chart1.ChartAreas[0].AxisY.Minimum = 200;
}
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
chart1.Series["Series1"].Points.Clear();
chart1.Series["Series2"].Points.Clear();
string selected = comboBox1.Text;
// label1.Text = dateTimePicker1.Value.ToString("yyyy/MM/dd");
SqlConnection con = new SqlConnection(#"server=HIST;database=PLC_DB;uid=sa;password=NCADMIN#123;MultipleActiveResultSets=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT top (10) * FROM [PLC_DB].[dbo].[EVEREST] WHERE [DATESTR] > DATEADD(HOUR, - " + selected + ", GETDATE())", con);
cmd.ExecuteNonQuery();
dr1 = cmd.ExecuteReader();
while (dr1.Read())
{
chart1.Series["Series1"].Points.AddXY(dr1["Tag1"].ToString(), dr1["TagValue1"].ToString());
chart1.Series["Series2"].Points.AddXY(dr1["Tag2"].ToString(), dr1["TagValue2"].ToString());
chart1.ChartAreas[0].AxisX.Enabled = System.Windows.Forms.DataVisualization.Charting.AxisEnabled.True;
chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series[1].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series["Series1"].IsValueShownAsLabel = true;
chart1.Series["Series2"].IsValueShownAsLabel = true;
//chart1.Series["Series2"].Label
}
con.Close();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
dateTimePicker1 = new DateTimePicker();
dateTimePicker1.Format = DateTimePickerFormat.Time;
dateTimePicker1.ShowUpDown = true;
}
private void button2_Click(object sender, EventArgs e)
{
chart1.Series["Series1"].Points.Clear();
string selected = comboBox1.Text;
// label1.Text = dateTimePicker1.Value.ToString("yyyy/MM/dd");
SqlConnection con = new SqlConnection(#"server=HIST;database=PLC_DB;uid=sa;password=NCADMIN#123;MultipleActiveResultSets=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [PLC_DB].[dbo].[TEMP] WHERE [DATESTR] > DATEADD(HOUR, - " + selected + ", GETDATE())", con);
cmd.ExecuteNonQuery();
dr1 = cmd.ExecuteReader();
while (dr1.Read())
{
chart1.Series["Series1"].Points.AddXY(dr1["Tag"].ToString(), dr1["TagValue"].ToString());
chart1.Series["Series2"].Points.AddXY(dr1["Tag"].ToString(), dr1["TagValue"].ToString());
chart1.ChartAreas[0].AxisX.Enabled = System.Windows.Forms.DataVisualization.Charting.AxisEnabled.True;
chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series[1].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series["Series1"].IsValueShownAsLabel = true;
chart1.ChartAreas[0].AxisY.Maximum = 250;
chart1.ChartAreas[0].AxisY.Minimum = 200;
}
con.Close();
}
}
}
I am working on c# windows form where i have to show a trend for sql server data coming in on different date and time. There are two parameters one is DATESTR which is on X-axis and second is Values which is on Y-axis . Tooltip is only showing Y-axis values but unable to show X-axis Values. In chart, it is showing 0 as the value of x axis.

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;
}
}
}

put the System.Windows.Form.ComboBox in Datagridview

We want to attach a combo box into a cell of data grid view. Now it works with mouse click. but for faster moving of form we need it to work using keyboard.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void CreateGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add("EmpName", typeof(string));//0
dt.Columns.Add("EmpID", typeof(int));//1
dt.Columns.Add("PhoneNo", typeof(string));//2
dt.Columns.Add("Address", typeof(string));//3
dt.Columns.Add("Email", typeof(string));//4
dataGridView1.DataSource = dt;
dataGridView1.Controls.Add(comboBox1); // Add System.Windows.Form.ComboBox in Datagridview
}
private void Form1_Load(object sender, EventArgs e)
{
CreateGrid();
fillRecords(1);
}
string SQL;
void fillRecords(int QueryNo)
{
SqlConnection con = new SqlConnection(#"Data Source=APPLE-PC\RNS;Initial Catalog=DemoDatabase;User ID=sa;Password=rns11");
con.Open();
if (QueryNo==1)
{
SQL = "Select EmpName,EmpID from EmployeeMaster";
}
else if (QueryNo==2)
{
SQL = "Select PhoneNo,Address from EmployeeMaster where EmpID=" + comboBox1.SelectedValue.ToString();
}
SqlDataAdapter da = new SqlDataAdapter(SQL, con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if (QueryNo == 1)
{
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "EmpName";
comboBox1.ValueMember = "EmpID";
}
else if (QueryNo == 2)
{
dataGridView1.CurrentRow.Cells[1].Value = comboBox1.SelectedValue.ToString();
dataGridView1.CurrentRow.Cells[0].Value = comboBox1.Text;
DataRow dr=dt.Rows[0];
dataGridView1.CurrentRow.Cells[2].Value = dr["PhoneNo"];
dataGridView1.CurrentRow.Cells[3].Value = dr["Address"];
}
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
//Visible Location on Current Cell
if (dataGridView1.CurrentCell.ColumnIndex==0)
{
comboBox1.Visible = true;
comboBox1.Location = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
comboBox1.Size = dataGridView1.CurrentCell.Size;
}
}
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
comboBox1.Visible = false;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue.ToString()!="System.Data.DataRowView")
{
fillRecords(2);
}
}
}
this solution is given by Sinisa Hajnal.
It should work using keyboard, but usually need to press F2 first to enter edit mode. I can solve this by handling CellEnter event and opening edit mode for combobox and setting focus to it inside.
`
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex==0)
{
comboBox1.Visible = true;
comboBox1.Location = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
comboBox1.Size = dataGridView1.CurrentCell.Size;
comboBox1_SelectedIndexChanged(null, null);
comboBox1.Focus();//focus on Combobox
}
}
`

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.

Getting an errors after change the files name

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?

Categories