update Cascading combobox problem C# - c#

i have a simple question
i have a form which contain two related combo boxes but i have problem in updating the second dropdown content
this is the code
private void DiaryForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'expensesDataSet.Item' table. You can move, or remove it, as needed.
// this.itemTableAdapter.Fill(this.expensesDataSet.Item);
using (OleDbConnection con = dbconn.dbconnection())
{
ds1 = new ExpensesDataSet();
string sql = "SELECT * From DiaryView";
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
da.Fill(ds1, "DiaryView");
NavigateRecords();
MaxRows = ds1.Tables["DiaryView"].Rows.Count;
//fill category combobox
string sqlcat = "SELECT * From Category";
catda = new System.Data.OleDb.OleDbDataAdapter(sqlcat, con);
catda.Fill(ds1, "Category");
catda.Update(ds1, "Category");
comboBox2.DataSource=ds1.Tables["Category"];
comboBox2.DisplayMember = "cat_name";
comboBox2.ValueMember="cat_id";
//comboBox1.Enabled = false;
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
using (OleDbConnection con = dbconn.dbconnection())
{
if (comboBox2.Items.Count > 0)
{
{
string cat = comboBox2.SelectedValue.ToString();
comboBox1.Enabled = true;
int catid = int.Parse(comboBox2.SelectedValue.ToString());
string sqlitem = "SELECT * From Item where cat_id = " + catid;
catda = new System.Data.OleDb.OleDbDataAdapter(sqlitem, con);
this.itemBindingSource.EndEdit();
catda.Fill(ds1, "Item");
catda.Update(ds1, "Item");
comboBox1.DataSource = ds1.Tables["Item"];
comboBox1.DisplayMember = "item_name";
comboBox1.ValueMember = "item_id";
}
}
}
}
there is two tables:
category(cat_id,cat_name)
item(item_id,item_name,cat_id)
what can i do??
plz help :)

If you want to clear the combobox, just do:
combobox1.Items.Clear();
It's as easy as that.

Related

refreshing DataSource Master-Detail XtraGrid

i have this code that create Master-Detail XtraGrid at runtime
public partial class FRM_Reserved : DevExpress.XtraEditors.XtraForm
{
DataTable Table1 = new DataTable("Table1");
DataTable Table2 = new DataTable("Table2");
DataSet dataSet = new DataSet();
public FRM_Reserved()
{
InitializeComponent();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables["Table1"].Columns["Bon N"],
dataSet.Tables["Table2"].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables["Table1"];
}
I want to refreshing DataSource on a click of button so I added this code
private void btnRefresh_Click(object sender, EventArgs e)
{
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}
but the code does not work ,can you help me please.
Try below code. Hope it works
private void btnRefresh_Click(object sender, EventArgs e)
{
gridControl3.DataSource=null;
gridControl3.Items.Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}
the problem was in the name of the tables it change every time
dataSet.Tables[(Table1.TableName)]
dataSet.Tables[(Table2.TableName)]
so I made this changes
private void simpleButton1_Click(object sender, EventArgs e)
{
dataSet.Relations.Clear();
dataSet.Tables["Table2"].Clear();
dataSet.Tables["Table1"].Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables[(Table1.TableName)].Columns["Bon N"],
dataSet.Tables[(Table2.TableName)].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables[(Table1.TableName)];
gridControl3.ForceInitialize();
}
Thanks for helping me
Use the following code
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.RefreshDataSource();
Try this one
private void button1_Click(object sender, EventArgs e)
{
var ds = new DataSet();
var dt1 = GetTable1Data();
var dt2 = GetTable2Data();
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
ds.Relations.Add("RelationTable",
ds.Tables["Table1"].Columns["col1"],
ds.Tables["Table2"].Columns["col1"]);
gridControl1.DataSource = ds.Tables["Table1"];
gridControl1.RefreshDataSource();
}
private DataTable GetTable1Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
using (var cmd = new SqlCommand("Stored procedure name goes here", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}
private DataTable GetTable2Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
const string sql = "SELECT * FROM Table2";
using (var cmd = new SqlCommand(sql, conn))
{
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}

Binding Combobox with database

I have combobox in my form which display value from database. I want one default value so I use .text property also and on selected index changed event the label display the corresponding value of the database the code is not working
string cstr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
private void AddStock_Load(object sender, EventArgs e)
{
bindcombo();
}
private void bindcombo()
{
SqlConnection con = new SqlConnection(cstr);
SqlDataAdapter da = new SqlDataAdapter("SELECT Dname FROM dealer", con);
DataTable dt = new DataTable();
da.Fill(dt);
cmbdealer.DataSource = dt;
cmbdealer.DisplayMember = "Dname";
cmbdealer.Text = "select-Dealer";
con.Close();
}
private void cmbdealer_SelectedIndexChanged(object sender, EventArgs e)
{
dealerdetails();
}
private void dealerdetails()
{
SqlConnection con = new SqlConnection(cstr);
SqlCommand cmd = new SqlCommand("select * from dealer where Dname='" + cmbdealer.Text + "'", con);
con.Open();
SqlDataReader re = cmd.ExecuteReader();
while (re.Read())
{
lbdl.Text = re["Ddlno"].ToString();
lbgst.Text = re["Dgstno"].ToString();
lbadd.Text = re["Daddress"].ToString();
}
}
the above code is working fine but when the form is load all the 3 label shows the database value of the first entry of my dealer table without selecting and value from combobox.

Autocomplete with Int values

I have this method auto complete for names(string),
i want to create other method that completes Int Type, i try it but it says
cannot use LIKE for int type only for string
void AutoComplete()
{
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection Collection = new AutoCompleteStringCollection();
con.Open();
cmd = new SqlCommand("select * from stagiaire",con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
nom = dr.GetString(1).ToString();
Collection.Add(nom);
}
textBox1.AutoCompleteCustomSource = Collection;
con.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("nom like '{0}%'", textBox1.Text);
dataGridView1.DataSource = dv;
}
private void Form1_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("select * from stagiaire",con);
da.Fill(dt);
}
for Column with DataType INTEGER use query like this:
select * from Table where Id like 1;
or convert it in to varchar:
select * from Table where CAST(Id AS VARCHAR(45)) like '1%'

i want to generate two combo box dynamically ,and want to bind them together at the same time

for example: I generate two combo-boxes box1 and box2 dynamically(on run time with a add button click) and on the selected index change of box1, items in box2 should be changed ;data in both boxes is fetched from database.
int cnt = 0;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection conb = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
public Form2()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
cnt++;
AddNewComboBox();
AddNewComboBox1();
}
private void AddNewComboBox()
{
ComboBox myNewComboBox = new ComboBox();
myNewComboBox.Name = "ComboBox1" + cnt.ToString();
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from company", con);
DataSet ds = new DataSet();
adp.Fill(ds, "company");
myNewComboBox.DataSource = ds.Tables["company"];
myNewComboBox.DisplayMember = ds.Tables["company"].Columns[0].ToString();
myNewComboBox.ValueMember = ds.Tables["company"].Columns[0].ToString();
//Program.counteritems = myNewComboBox.SelectedValue.ToString();
myNewComboBox.SelectedIndexChanged += new EventHandler(myNewComboBox_SelectedIndexChanged);
flowLayoutPanel1.Controls.Add(myNewComboBox);
con.Close();
}
private void AddNewComboBox1()
{
//string xyz = Program.counteritems;
ComboBox myNewComboBox1 = new ComboBox();
myNewComboBox1.Name = "ComboBox2" + cnt.ToString();
conb.Open();
SqlDataAdapter adp1 = new SqlDataAdapter("select * from company", con);
DataSet ds1 = new DataSet();
adp1.Fill(ds1, "company");
myNewComboBox1.DataSource = ds1.Tables["company"];
myNewComboBox1.DisplayMember = ds1.Tables["company"].Columns[1].ToString();
myNewComboBox1.ValueMember = ds1.Tables["company"].Columns[1].ToString();
//myNewComboBox_SelectedIndexChanged(sender);
myNewComboBox1.SelectedIndexChanged += new EventHandler(myNewComboBox1_SelectedIndexChanged);
flowLayoutPanel2.Controls.Add(myNewComboBox1);
//changefunction();
conb.Close();
}
void myNewComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var cbox1 = sender as ComboBox;
if (cbox1 != null)
{
if (cbox1.Name == "ComboBox1" + cnt.ToString())
{
var cbox2 = flowLayoutPanel2.Controls.OfType<ComboBox>().Where(c => c.Name == "ComboBox2" + cnt.ToString()).FirstOrDefault();
cbox2.SelectedValue = cbox1.SelectedValue.ToString();
con2.Open();
SqlDataAdapter adfgtyu = new SqlDataAdapter("select * from Cat_Comp_Item where (Category_Name='" + cbox1.SelectedText + "') ", con2);
DataSet dsft = new DataSet();
adfgtyu.Fill(dsft, "Cat_Comp_Item");
cbox2.DataSource = dsft.Tables["Cat_Comp_Item"];
cbox2.DisplayMember = dsft.Tables["Cat_Comp_Item"].Columns[1].ToString();
con2.Close();
}
}
//string combochange1 = ((ComboBox)sender).Text;
//if (!string.IsNullOrEmpty(myNewComboBox.SelectedValue.ToString()))
//{
// myNewComboBox1.SelectedValue = myNewComboBox.SelectedValue.ToString();
//}
}
private void Form2_Load(object sender, EventArgs e)
{
AddNewComboBox();
AddNewComboBox1();
}
void myNewComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Press OK to select this ");
}
I think you should bind first combobox value and second combobox add just text(---select---) on add button and letter on first combobox index change bind second combobox
You can do as below
private void myNewComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var cbox1 = sender as ComboBox;
if (cbox1 != null)
{
if (cbox1.Name == "ComboBox1")
{
var cbox2 = flowLayoutPanel2.Controls.OfType<ComboBox>().Where(c => c.Name == "ComboBox2").FirstOrDefault();
cbox2.SelectedValue = cbox1.SelectedValue.ToString();
}
}
}
To Do that you need to set comboBox2.ValueMember and comboBox1.ValueMember as same column in your company Table. select ID column or primary key column for that.
And also name your comboboxes as ComboBox1 and ComboBox2 when you create it like below
ComboBox myNewComboBox = new ComboBox();
myNewComboBox.Name = "ComboBox1";
And do the same for ComboBox2

Delete row from datagridview

I having problem on deleting a row of data returned by a search query.
I wish the user can select whichever row of data and click on the delete button [button1_click] to delete it from DB. This is a windows form application.
Hope you can advise me. Thanks a lot.
Below is my code
public partial class Search : Form
{
public Search()
{
InitializeComponent();
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable ds = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM staff", cn))
{
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
adp.Fill(ds);
comboBox1.DataSource = ds;
comboBox1.ValueMember = "sname";
comboBox1.SelectedIndex = 0;
}
}
}
private void btn_search_bystaffname_Click(object sender, EventArgs e)
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable dt = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE sname = #sname", cn))
{
//cmd.Parameters.AddWithValue("#bdate", dtp_search_date.Value.Date);
cmd.Parameters.AddWithValue("#sname", comboBox1.SelectedValue);
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
oda.Fill(dt);
GridView1.DataSource = dt;
GridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[3].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[0].HeaderText = "Booking ID";
GridView1.Columns[1].HeaderText = "Client Name";
GridView1.Columns[2].HeaderText = "Booking Date";
GridView1.Columns[3].HeaderText = "Booking Time";
GridView1.Columns[4].HeaderText = "Client Contact";
GridView1.Columns[5].HeaderText = "Staff Name";
this.GridView1.DefaultCellStyle.Font = new Font("Times New Roman", 12);
this.GridView1.DefaultCellStyle.ForeColor = Color.Blue;
this.GridView1.DefaultCellStyle.BackColor = Color.Beige;
this.GridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
this.GridView1.DefaultCellStyle.SelectionBackColor = Color.Black;
this.GridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
}
}
}
private void btn_search_bydate_Click(object sender, EventArgs e)
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable dt = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE bdate = #bdate", cn))
{
cmd.Parameters.AddWithValue("#bdate", dtp_search_date.Value.Date);
cmd.Parameters.AddWithValue("#sname", comboBox1.SelectedValue);
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
oda.Fill(dt);
GridView1.DataSource = dt;
GridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[3].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[0].HeaderText = "Booking ID";
GridView1.Columns[1].HeaderText = "Client Name";
GridView1.Columns[2].HeaderText = "Booking Date";
GridView1.Columns[3].HeaderText = "Booking Time";
GridView1.Columns[4].HeaderText = "Client Contact";
GridView1.Columns[5].HeaderText = "Staff Name";
this.GridView1.DefaultCellStyle.Font = new Font("Times New Roman", 12);
this.GridView1.DefaultCellStyle.ForeColor = Color.Blue;
this.GridView1.DefaultCellStyle.BackColor = Color.Beige;
this.GridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
this.GridView1.DefaultCellStyle.SelectionBackColor = Color.Black;
this.GridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
GridView1.Rows.Remove(row);
}
}
}
I'm assuming this is the method you want to change
private void button1_Click(object sender, EventArgs e)
{
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
GridView1.Rows.Remove(row);
}
This GridView1.Rows.Remove(row); will only remove the item from the DaDataGridViewRowCollection and will not remove it from the database.
To remove it from the database you can do one of the following
Remove it from `DataTable' and then use a DataAdapter and call update.
Directly delete it from the database using a DELETE SQL statement through a OleDbCommand.
If you choose option one you'd be well served by making dt a Field on your Form. This is because you can only access it now via ((DataRow)row.DataBoundItem).Table or GridView1.DataSource in the button1_Click event. Also making the DataAdapter a field would make this easier
e.g.
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
DataRow dRow = (DataRow)row.DataBoundItem;
dt.Rows.Remove(dRow);
Adapter.Update(dt);
As an aside you can choose to do only the dt.Rows.Remove(dRow); in the button1_Click and defer the Adapter.Update(dt) until later in a Save button.
If you go with option two you'll need to remove it from the DataTable or refresh the DataTable
e.g.
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
OleDbCommand cmd = new OleDbCommand(
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
// not 100% this delete syntax is correct for Access
using (var cmd = new OleDbCommand("DELETE booking WHERE [Booking ID] = #BookingId", cn))
{
cmd.Parameters.AddWithValue("#BookingId", dRow["Booking Id"]);
cmd.ExecuteNonQuery();
}
}
// Do this to update the in-memory representation of the Data
DataRow dRow = (DataRow)row.DataBoundItem;
dt.Rows.Remove(dRow);
// Or just refresh the datatable using code similar as your search methods
Here's how I've been doing it in my application (My unique identifier for the mysql table is in cell zero):
Oh, and dtcommand is a class instance for a database command class I use for common db stuff.
int userDeleteIndex;
if (int.TryParse(datagridview.Rows[rowIndex].Cells[0].Value.ToString(), out userDeleteIndex))
{
if (MessageBox.Show("Delete " + recordidentifyingdata + "? ", "Delete " + userDeleteIndex.ToString(), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
string updateUserSql = "DELETE FROM table WHERE user_id = " + userDeleteIndex.ToString() + "; ";
dtCommand.UpdateTable(updateUserSql);
InitializeUserDataView();
// Initalize userdataview refreshes the datagridview with the updated info
}
catch (Exception err)
{
Error trapping goes here
}
Here's the database update section from my class:
public int UpdateTable(string updateString, string MySqlConnectionString)
{
int returnValue = 0;
MySqlConnection connection = new MySqlConnection(MySqlConnectionString);
MySqlCommand command = new MySqlCommand(updateString, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception err)
{
WriteErrorLog("Unable to update table: " + err.ToString() +
" - Using SQL string: " + updateString + ".");
//MessageBox.Show("An error has occured while updating the database.\n" +
//"It has been written to the file: " + errorFile + ".", "Database Error");
returnValue = -1;
}
finally
{
connection.Close();
}
return (returnValue);
}

Categories