Refresh Combobox from SQL Server 2008 - c#

I'm starting with C # and I meet some problems.
I would like to know how to refresh the data, when I save data in the second windows form (agregar_en_directorio)
and want to display the new data in the combo box of the first windows form (generar_tarjeta).
The Conexion: conectaraBD.cs
public static SqlConnection ObtenerCOnexion()
{
SqlConnection Conn = new SqlConnection(#"Data source=MY-PC\SQLEXPRESS; Initial Catalog=myDatabase; User Id=user; Password=xxxx");
Conn.Open();
return Conn;
}
The Combo:
public void fillCombo()
{
string SQL = "select id_persona as identificador, clave_de_identificacion +' '+clave_de_la_dependencia +' '+grado_o_titulo+' '+nombre+' '+ ap+' '+ am DetallesCompletos from directorio";
DataTable dt = new DataTable();
using (SqlConnection Conn2 = conectaraBD.ObtenerCOnexion())
{
using (var cmd = new SqlCommand(SQL, Conn2))
{
try
{
dt.Load(cmd.ExecuteReader());
}
catch (SqlException e)
{
MessageBox.Show("Error al Cargar los Datos" + e.ToString(), "Error SQL",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
comboDe.DataSource = dt;
comboDe.ValueMember = "identificador";
comboDe.DisplayMember = "DetallesCompletos";
}
Note: The used code for the combobox is the follow (used similars for the 3 combobox).
And would help me your opinion of the GUI

i solved, but I had to change some things:
public static DataTable dataFortheCombos()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(#"Data source=SAMANIEGO-PC\SQLEXPRESS; Initial Catalog=banco_de_datos; User Id=user; Password=xxx");/
string query = "select id_person as identifier, identification_key +' '+dependence_key +' '+degree_or_title+' '+name+' '+ ap+' '+ am as completedetails from directory";
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(dt);
return dt;
}
public static AutoCompleteStringCollection autocompleteCombos()
{
DataTable dt = dataFortheCombos();
AutoCompleteStringCollection coleccion = new AutoCompleteStringCollection();
foreach (DataRow row in dt.Rows)
{
coleccion.Add(Convert.ToString(row["completedetails"]));
}
return coleccion;
}
public void fillCombos()
{
comboFrom.DataSource = dataFortheCombos();
comboFrom.DisplayMember = "completedetails"; //This is the value shown on the combo for the user
comboFrom.ValueMember = "identifier"; // The selectedc value insert as identifier (is a number)
comboFrom.SelectedIndex = -1; //Clear the combo
//NOTE -> The others combos (urned over and sender) using the same data
}
The event --onfocus-- is used to call the refresh when the user is located in the combobox comboFrom
private void comboDe_Enter(object sender, EventArgs e)
{
comboFrom.DataSource = null //Clear the Combo Box
//NOTE -> The others combos (urned over and sender) using the same data
fillCombos();
}

Related

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll (SqlTransaction)

Additional information invalid transaction closed the connection
Hello. I am developing a project to be used in SAP B1. I want to transfer rows from one table to another and delete these transferred rows from the table above. This process is taking place.
I want to save the rows transferred to the sub-table to a user-defined field in SAP with a button later. But I'm getting the error in the title on this line:
SqlTransaction transaction = con.BeginTransaction();
Here is my codes:
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(#"Data Source = *.***.***.**; Initial Catalog = SBODemoTR; User ID = sa ; Password = ******10601");
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter sda = new SqlDataAdapter("SELECT T0.[CardName] AS 'MÜŞTERİ', T0.[DocNum] AS 'SİPARİŞ NO', T1.[ItemCode] AS 'SATIŞ NO', T1.[Dscription] AS 'KALEM TANIMI', T0.[DocDueDate] AS 'PLANLANAN TESLİM TARİHİ', T1.[Quantity] AS 'SİPARİŞ MİKTARI' FROM ORDR T0 INNER JOIN RDR1 T1 ON T0.[DocEntry] = T1.[DocEntry] WHERE T0.[DocStatus] = 'O' ", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = false; // Select butonlarının seçili olmadan gelmesini sağlar.
dataGridView1.Rows[n].Cells[1].Value = item["MÜŞTERİ"].ToString();
dataGridView1.Rows[n].Cells[2].Value = item["SİPARİŞ NO"].ToString();
dataGridView1.Rows[n].Cells[3].Value = item["SATIŞ NO"].ToString();
dataGridView1.Rows[n].Cells[4].Value = item["KALEM TANIMI"].ToString();
dataGridView1.Rows[n].Cells[5].Value = item["PLANLANAN TESLİM TARİHİ"].ToString();
dataGridView1.Rows[n].Cells[6].Value = item["SİPARİŞ MİKTARI"].ToString();
}
}
.......
private void button4_Click(object sender, EventArgs e)
{
string constring = #"Data Source = *.***.***.**; Initial Catalog = SBODemoTR; User ID = sa ; Password = *******01";
SqlConnection con = new SqlConnection(constring);
SqlTransaction transaction = con.BeginTransaction();
try
{
con.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO #ODS_HFTURETIM ([MÜŞTERİ], [SİPARİŞ NO], [SATIŞ NO], [KALEM TANIMI], [PLANLANAN TESLİM TARİHİ], [SİPARİŞ MİKTARI])VALUES(#MÜŞTERİ, #SİPARİŞ NUMARASI, #SATIŞ NUMARASI, #KALEM TANIMI, #PLANLANAN TESLİM TARİHİ, #SİPARİŞ MİKTARI])", con))
{
cmd.Parameters.AddWithValue("#MÜŞTERİ", row.Cells["MÜŞTERİ"].Value);
cmd.Parameters.AddWithValue("#SİPARİŞ NUMARASI", row.Cells["SİPARİŞ NUMARASI"].Value);
cmd.Parameters.AddWithValue("#SATIŞ NUMARASI", row.Cells["SATIŞ NUMARASI"].Value);
cmd.Parameters.AddWithValue("#KALEM TANIMI", row.Cells["KALEM TANIMI"].Value);
cmd.Parameters.AddWithValue("#PLANLANAN TESLİM TARİHİ", row.Cells["PLANLANAN TESLİM TARİHİ"].Value);
cmd.Parameters.AddWithValue("#SATIŞ MİKTARI", row.Cells["SATIŞ MİKTARI"].Value);
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();
}
}
transaction.Commit();
con.Close();
MessageBox.Show("Başarılı Bir Şekilde Kaydedildi!");
}
catch (Exception ex)
{
transaction.Rollback();
con.Close();
MessageBox.Show(ex.Message);
}
FillData
FillData2
This is the picture you should see :

How to enter more than 1 row into dataGridView from textBox search

I am using the below code to search for the inputted textBox ID in an accessdb and returning the row of data to a dataGridView. When I search for a second ID, the first row in the GridView is replaced, How can I make it save multiple rows?
The end goal of this project is to allow the user to search as many ID's as they like and pull the corresponding row of data into the gridview to then save all into a csv.
private void searchButton_Click(object sender, EventArgs e)
{
conn1.Open();
//return ID, IMEI, ICCID, IMSI from dataBase
OleDbCommand cmd1 = new OleDbCommand("Select ID, IMEI,ICCID, IMSI from TBL where ID=#param1", conn1);
cmd1.Parameters.AddWithValue("#param1", txtScannedValue.Text);
OleDbDataReader reader1;
reader1 = cmd1.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader1);
//dataGridView1.DataSource= dt;
if (dt.Rows.Count > 0)
{
((DataTable)dataGridView1.DataSource).ImportRow(dt.Rows[0]);
}
else
{
MessageBox.Show("No Data Found");
}
//reset textBox
txtScannedValue.Text = "";
conn1.Close();
}
What you are doing is - each time you press the searchButton_Click button you are running a query that returns 1 row only(ID=#param1) and then you are inserting ALL(which is always 1 in your case due to query) your searched rows to your dataGridView via .DataSource() bind.
To solve this I would recommend you to re-implement your data bindings:
I am assuming that DataTable is from ADO.NET so without changing a query you could bind your data something like this:
// this is pseudocode
private void searchButton_Click(object sender, EventArgs e) {
var row = (DataGridViewRow) dataGridView1.Rows[0].Clone();
var retrievedRow = getRowById(txtScannedValue.Text);
if (retrievedRow is null) return;
row.Cells[0].Value = retrievedRow.value1; // bind here you model fields
row.Cells[1].Value = retrievedRow.value2;
// ...
dataGridView1.Rows.Add(row);
}
private void getRowById(string id) {
conn1.Open();
OleDbCommand cmd1 = new OleDbCommand("Select ID, IMEI, TekNum, BatchNum, ICCID, IMSI from TBLTest1 where ID=#param1", conn1);
cmd1.Parameters.AddWithValue("#param1", id);
OleDbDataReader reader1;
reader1 = cmd1.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader1);
DataRow row;
if (dt.Rows.Count > 0) {
row = dt.Rows[0];
}
conn1.Close();
return row;
}
I'd use a ListBox or ComboBox to present data they can recognize with the id available. To append rows, use DataTable.ImportRow.
Here a ComboBox is used to present, in this case employees and the DataGridView is initially populated with an empty DataTable.
Click a button to get a row to append to the underlying DataTable for the DataGridView.
Model and data operations
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
namespace AccessApplication.Classes
{
public class EmployeesOperations
{
public static string ConnectionString =>
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=NorthWind.accdb";
public static List<Employee> EmployeesList()
{
List<Employee> list = new List<Employee>();
using var cn = new OleDbConnection { ConnectionString = ConnectionString };
using var cmd = new OleDbCommand() { Connection = cn };
cmd.CommandText = "SELECT EmployeeID, FirstName, LastName FROM Employees";
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
list.Add(new Employee()
{
Id = reader.GetInt32(0),
FirstName = reader.GetString(1),
LastName = reader.GetString(2)
});
}
return list;
}
public static DataTable EmptyDataTable()
{
using var cn = new OleDbConnection { ConnectionString = ConnectionString };
using var cmd = new OleDbCommand() { Connection = cn };
cmd.CommandText =
"SELECT TOP 1 EmployeeID, FirstName, LastName FROM Employees";
cn.Open();
DataTable table = new DataTable();
table.Load(cmd.ExecuteReader());
table.Rows.Clear();
return table;
}
public static DataTable SingleRow(int identifier)
{
using var cn = new OleDbConnection { ConnectionString = ConnectionString };
using var cmd = new OleDbCommand() { Connection = cn };
cmd.CommandText =
"SELECT TOP 1 EmployeeID, FirstName, LastName " +
"FROM Employees WHERE EmployeeID = #Id";
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = identifier;
cn.Open();
DataTable table = new DataTable();
table.Load(cmd.ExecuteReader());
return table;
}
}
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString() => $"{FirstName} {LastName}";
}
}
Form code
public partial class EmployeeForm : Form
{
private readonly BindingSource _employeesBindingSource =
new BindingSource();
public EmployeeForm()
{
InitializeComponent();
_employeesBindingSource.DataSource = EmployeesOperations.EmployeesList();
EmployeesComboBox.DataSource = _employeesBindingSource;
dataGridView1.DataSource = EmployeesOperations.EmptyDataTable();
}
private void GetSingleEmployeeButton_Click(object sender, EventArgs e)
{
int id = ((Employee)EmployeesComboBox.SelectedItem).Id;
DataTable table = ((DataTable)dataGridView1.DataSource);
DataRow result = table.AsEnumerable()
.FirstOrDefault(row => row.Field<int>("EmployeeID") == id);
// only add if not already in the data grid view
if (result == null)
{
table.ImportRow(EmployeesOperations.SingleRow(id).Rows[0]);
}
}
}
The below code is now working for using the textbox to search the database and enter multiple rows of code into the dataGridView. The question was answered in the comments on the op by JohnG. Posting here for future reference.
private void searchButton_Click(object sender, EventArgs e)
{
conn1.Open();
//return ID, IMEI, BatchNum, ICCID, IMSI from dataBase
OleDbCommand cmd1 = new OleDbCommand("Select ID, IMEI, BatchNum, ICCID, IMSI from TBLTest1 where ID=#param1", conn1);
cmd1.Parameters.AddWithValue("#param1", txtScannedValue.Text);
OleDbDataReader reader1;
reader1 = cmd1.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader1);
if (dt.Rows.Count > 0)
{
if (dataGridView1.DataSource != null) {
((DataTable)dataGridView1.DataSource).ImportRow(dt.Rows[0]);
}
else
{
dataGridView1.DataSource = dt;
}
}
else
{
MessageBox.Show("No Data Found");
}
//reset textBox
txtScannedValue.Text = "";
conn1.Close();
}

C# C0246 While Filtering DataGridView with Listbox whose items come from SQL Server

I share with you a piece of code that works except the part where I'm trying to loop in the items of my listbox. That's why I'm here asking you for some help.
Lately, I switched from VBA to C# so I'm still new on this and don't undertsand everything yet.
So, the below code connect to my SQL server DB and fetch data both within my listbox and a DataGridView. I can filter with two textboxes also.
So now I have items within my listbox and my db's view within the DataGridview. I'd like to filter my DataGridview (which is filled by a datatable ) with my Listbox's item. I miss only a silly part I guess. Why Do I get this CS0246 "ListItem could not be found"
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsAppTest
{
public partial class Form1 : Form
{
//Initialize the component and display the items within my listbox CS_Bonds_listBox
public Form1()
{
InitializeComponent();
string connetionString = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(connetionString);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT DISTINCT RatingProvider FROM Bonds", conn);
adapter.Fill(ds);
this.CS_Bonds_listBox.DataSource = ds.Tables[0];
this.CS_Bonds_listBox.DisplayMember = "RatingProvider";
}
private void Form1_Load(object sender, EventArgs e)
{
}
DataTable dtTEST = new DataTable();
// Next, when clicking on my button Connect, I retrieve my db into a Datatable that is displayed within //the Datagridview1
private void buttonConnect_Click(object sender, EventArgs e)
{
string connetionString = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
SqlConnection cnn= new SqlConnection(connetionString);
cnn.Open();
MessageBox.Show("Connection Open !");
String sql = "Select * from Bonds";
SqlCommand command = new SqlCommand(sql, cnn);
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = command;
sqlDA.Fill(dtTEST);
dataGridView1.DataSource = dtTEST;
cnn.Close();
}
private void ISIN_Bonds_textBox_TextChanged(object sender, EventArgs e)
{
DataView dv = dtTEST.DefaultView;
dv.RowFilter = "ISIN LIKE '" + ISIN_Bonds_textBox.Text + "%'";
dataGridView1.DataSource = dv;
}
private void Ticker_Bonds_textBox_TextChanged(object sender, EventArgs e)
{
DataView dv1 = dtTEST.DefaultView;
dv1.RowFilter = "Ticker LIKE '" + Ticker_Bonds_textBox.Text + "%'";
dataGridView1.DataSource = dv1;
}
private void CS_Bonds_listBox_SelectedIndexChanged(object sender, EventArgs e)
{
string conString = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
string query = "SELECT ISIN, Ticker, CrediSight, FROM Bonds";
string condition = string.Empty;
foreach (ListItem item in CS_Bonds_listBox.Items)
{
condition += item.Selected ? string.Format("'{0}',", item.Value) : "";
}
if (!string.IsNullOrEmpty(condition))
{
condition = string.Format(" WHERE Country IN ({0})", condition.Substring(0, condition.Length - 1));
}
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query + condition))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.Connection = con;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
//dataGridView1.DataBind();
}
}
}
}
}
}
}
This line has a problem:
foreach (ListItem item in CS_Bonds_listBox.Items)
A ListItem is a WebForms thing, and your application is a WinForms thing; your listbox doesn't contain a list of ListItem objects so this line of code wouldn't work out anyway, even if the relevant web namespace was imported.
Because you've bound your listbox to a datatable the list it is showing is full of DataRowView objects, so that's what you need to process. A DataRowView has a Row property that gives you the underlying row, which in turn can be accessed by a column name.
Additionally, to make your life easier a listbox has a SelectedItems property so you don't need to check every item for being selected:
foreach (DataRowView drv in CS_Bonds_listBox.SelectedItems)
{
var dr = drv.Row as DataRow;
var rp = dr["RatingProvider"];
condition += $"'{rp}',"
}
Your condition will end up with a trailing comma as a result of this, so trim it off before you build an IN clause with it:
condition = condition.TrimEnd(',');
This technique could be susceptible to SQL Injection hacking if the user manages to change the text showing in the list items.
A better way to handle the problem is via parameterization. You'd do it like this:
var cmd = new SqlCommand("SELECT * FROM table WHERE Country IN(", connStr);
int i = 0;
foreach (DataRowView drv in CS_Bonds_listBox.SelectedItems)
{
var dr = drv.Row as DataRow;
var rp = dr["RatingProvider"];
cmd.CommandText += $"#p{i},";
cmd.Parameters.Add($"#p{i}", SqlDbType.VarChar).Value = rp;
i++;
}
cmd.CommandText = cmd.CommandText.TrimEnd(',') + ")";
using(var da = new SqlDataAdapter(cmd))
{
var dt = new DataTable();
da.Fill(dt);
someGridView.DataSource = dt;
}
This builds an sql that looks like SELECT * FROM table WHERE Country IN(#p0,#p1,#p2.... i.e. we have concatenated parameter placeholders in rather than concatenating values in. At the same time we have filled the parameters collection with the parameter values
It also means that our database can't be hacked via our program, and our app doesn't die in a heap when the user selects a country with a name like Cote d'Ivoire
Some other things to note to tidy your code up:
SqlDataAdapter can take a string SQL and a string connection-string. You don't need to make a SqlCommand for it. You don't need to open and close conenctions for it; it knows how to do all this itself. I only used a SqlCommand because I was building the parameters collection as I went. Ordinarily I'd do using(var da = SqlDataAdapter("SELECT...", "Server=..") because it makes things nice and tidy.
This means e.g. your constructor can be simply:
//put this here once
private string _connStr = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
public Form1()
{
InitializeComponent();
var dt = new DataTable();
using(var da = new SqlDataAdapter("SELECT DISTINCT RatingProvider FROM Bonds", _connStr))
adapter.Fill(dt);
this.CS_Bonds_listBox.DataSource = dt;
this.CS_Bonds_listBox.DisplayMember = "RatingProvider";
}

Eliminating an option from a ComboBox (2), based on the input of the first ComboBox (1) c#

I am creating an airline booking system and I have 2 combo boxes. The first is for Departure City and the second is for Arrival City. I want to be able to eliminate the choice in the first combo box from the second, as I don't want the same city to be able to be submitted as both the departure and arrival city. I am querying the city names from a database.
Here is my code:
public partial class main : Form
{
public main()
{
InitializeComponent();
string connectionString = #"Base Schema Name=cyanair;data source=C:\Users\Client 0819\source\repos\Cyanair\cyanair.db";
//Departure ComboBox
SQLiteConnection conn = new SQLiteConnection(connectionString);
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM CyanairAirports";
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboDeparture.DataSource = dt;
comboDeparture.ValueMember = "Descriptions";
comboDeparture.DisplayMember = "Descriptions";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Arrival ComboBox
private void comboDeparture_DisplayMemberChanged(object sender, EventArgs e)
{
string connectionString = #"Base Schema Name=cyanair;data source=C:\Users\Client 0819\source\repos\Cyanair\cyanair.db";
SQLiteConnection conn = new SQLiteConnection(connectionString);
**String city = comboDeparture.DisplayMember;**
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM CyanairAirports WHERE Descriptions IS NOT '" + comboDeparture.SelectedValue.ToString() + "'";
richTextBox1.Text = "SELECT * FROM CyanairAirports WHERE Descriptions IS NOT '" + comboDeparture.SelectedValue + "'";
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboArrival.DataSource = dt;
comboArrival.ValueMember = "Descriptions";
comboArrival.DisplayMember = "Descriptions";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks :)
It looks like you're handling the DisplayMemberChanged event on comboDeparture, and trying to update the values of comboArrival in that handler. However, DisplayMemberChanged only triggers when the DisplayMember property changes.
DisplayMember only tells the control which property to display on a data bound control. It isn't tied to the index or value selected in the ComboBox. So, the only time the code to populate comboArrival runs is in the constructor when you set comboDepartarture.DisplayMember. Instead, handle either ComboBox.SelectedIndexChanged or ComboBox.SelectedValueChanged and set the items of comboArrival.
A few other important things to note about your code.
First, you should use a parameterized query when running Sql Statements, rather than concatenating strings. Concatenating strings as you're doing opens you up to SQL Injection Attacks. I'm not familiar with SqlLite and can't provide you with an example of how to modify your code, but perhaps this question can help.
Second, you don't need to re-run the query every time you change the selected value in comboDeparture. Just add comboArrival's data source as a field on the Form and you can filter it. For example...
public partial class main : Form
{
// Your constructors...
private void comboDepartures_SelectedIndexChanged(object sender, EventArgs e)
{
if (_arrivalsDataSource == null)
{
_arrivalsDataSource = new System.Data.DataTable();
// Load _arrivalsDataSource from the database, basically how you're doing it now.
comboArrival.DataSource = _arrivalsDataSource.DefaultView;
comboArrival.DisplayMember = "Descriptions"
comboArribal.ValueMember = "Descriptions"
}
if (comboDeparture.SelectedIndex == -1)
{
_arrivalsDataSource.DefaultView.RowFilter = null; // Clear the filter.
}
else
{
// Set the filter.
_arrivalsDataSource.DefaultView.RowFilter = $"Description <> '{comboDeparture.SelectedValue}'";
}
}
private System.Data.DataTable _arrivalsDataSource = null;
}

Combo Box on dropdown method only called once

I am using two combo boxes in one of my programs. The first combo box contains the products while the second contains the categories. I have a method which loads he categories on the second combo box from the database when ever a new item is selected on the first combo box "products". The first time i run the program and select an item it loads from the database but if i try it again nothing loads. Please help with what might be causing this.
private void load_schemes(object sender, EventArgs e)
{
DataTable subjects = new DataTable();
DBConnect con = new DBConnect();
using (SqlConnection CONN = con.getConnection())
{
try
{
schemename.Items.Clear();
SqlDataAdapter adapter = new SqlDataAdapter();
String schemeType = schemetype.Text;
firstname.Text = schemetype.Text;
String SQL = "";
if (schemeType == "Family Scheme")
{
SQL = "select schemeID,SCHEMENAME from registration.familyMedicalScheme";
}
else if (schemeType == "Insurance Scheme")
{
SQL = "select schemeID,SCHEMENAME from registration.insurancescheme";
}
else if (schemeType == "Company Scheme")
{
SQL = "select schemeID,SCHEMENAME from registration.companymedicalscheme";
}
adapter.SelectCommand = new SqlCommand(
SQL, CONN);
adapter.Fill(subjects);
schemename.DataSource = subjects;
schemename.DisplayMember = "SCHEMENAME";
//schemename.ValueMember = subjects.;
}
catch (Exception ex)
{
// Handle the error
}
finally
{
CONN.Close();
}
}
}
I changed the solution and used Items.Add instead of data binding method and it is now working
adapter.Fill(subjects);
foreach (DataRow da in subjects.Rows)
{
schemename.Items.Add(da[0].ToString());
}

Categories

Resources