Fill ComboBox with Access DB data - c#

I'm using Visual Studio 2010 and C# to create a windows form with a combobox that should contain employees initials. I have spent the last few days searching through every solution I can find and I still can not get my combobox to populate.
This is what I've got as of now:
public static void FillComboBox(string Query, System.Windows.Forms.ComboBox LoggedByBox)
{
using (var CONN = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Documents\\Service Request Application\\bin\\Debug\\servicereq1.mdb"))
{
CONN.Open();
DataTable dt = new DataTable();
try
{
OleDbCommand cmd = new OleDbCommand(Query, CONN);
OleDbDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
LoggedByBox.DataSource = dt;
LoggedByBox.ValueMember = "ID";
LoggedByBox.DisplayMember = "Initials";
}
}
Then I call it when the form loads
private void Form1_Load(object sender, EventArgs e)
{
FillComboBox("select ID, Initials from [Fixers and Testers]", LoggedByBox);
}
When I run the program, the combobox is still blank. I'm positive that my column names and table names are correct. Any suggestions?

I finally got my ComboBox filled and I wanted to share what I changed for anyone else who stumbles across this question in their searches. After spending a bit more time searching through other questions and MSDN, I was able to come up with this.
private void LoadComboLogged()
{
AppDomain.CurrentDomain.SetData("DataDirectory",#"\\prod\ServiceRequests");
string strCon = #"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\servicereq1.mdb";
try
{
using (OleDbConnection conn = new OleDbConnection(strCon))
{
conn.Open();
string strSql = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
DataSet ds = new DataSet();
adapter.Fill(ds);
loggedByComboBox.DataSource = ds.Tables[0];
loggedByComboBox.DisplayMember = "Initials";
loggedByComboBox.ValueMember = "Initials";
}
}
catch (Exception ex)
{
}
}
I also found that I needed to call
LoadComboLogged();
when I initialized my form. Without that line, the ComboBox would only show a blank dropdown list. Hope this helps someone else who runs into this problem.

Passing control to static method causing this issue. Instead of passing control to the method make that method returns the table and within the load method load the control.

SqlConnection con = new SqlConnection("Data Source=RUSH-PC\\RUSH;Initial Catalog=Att;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from userinfo", con);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dt.Rows.InsertAt(dr, 1);
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "name";
comboBox1.DataSource = dt;
con.Close();
This may help you...
Good luck...:-)

Another possible solution would be to query and return a list of strings. Perhaps it may be less efficient, but it's what I used in a recent project of mine. Here's an example that would reside in a method, possibly called GetInitialsFromDatabase():
using(var conn = new MySqlConnection(connectionString)
{
conn.Open();
using(MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
MySqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
// initials is a List<String> previously defined (Assuming strings)
initials.Add(String.Format("{0}", reader[0]));
}
}
conn.Close();
}
And then return the initials List, and then in your GUI you could say:
comboBox1.DataSource = returnedList;
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

Related

How to get data from SQL and write it in textbox?

I need a help.
I searched and I tried a lot but I am too bad to make it work on my project by myself.
This is code for button-Seek. I want to make Seek-button to fill textbox by respective data.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
var Conn = new SqlConnection();
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
var Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = " + Number;
var DataAdapter = new SqlDataAdapter(Cmd);
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
}
}
And This is the data table.
This is what happens when I put 3 in the text box and press Seek-button.
So here, I want all text boxes to be filled by the data which I searched.
You will get only one row for the query right?
So give like that,
txtFirstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
txtLasttName.Text = DataSet.Tables[0].Rows[0]["LastName"].ToString();
Like this you need to assign the values to the respective text boxes.
There are three problem need to fix.
You forget to open the connection with DB,add Conn.Open(); before you excute sql command.
You need to add parameter to prevention SQL Injection
Please use using it will help you to use external resources to return the memory.
when the DataSet be filled you can get the data then fill in textbox
You can follow like this.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
using (var Conn = new SqlConnection())
{
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
using (var Cmd = new SqlCommand())
{
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = #Number";
Cmd.Parameters.AddWithValue("#Number", Number);
//You miss to add Conn.Open()
Conn.Open();
using (var DataAdapter = new SqlDataAdapter(Cmd))
{
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
//when the DataSet be filled you can get the data then fill in textbox
txt_firstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
}
}
}
}
}

ComboBox with Suggest Ability based on Substring-Search or text match in list items of combox

This is how I am populating my combobox from database which is large quantity.
How i am search from list items in combobox as suggested not start from beginning it search also substring found inside of the string. and show all matching results in suggested list of combobox
{
SqlConnection connection = DBConnectivity.getConnection();
SqlCommand command;
string query;
DataSet dataset;
DataTable datatable;
SqlDataAdapter adapter;
SqlDataReader reader;
string[] ProductNameList;
public productform()
{
InitializeComponent();
}
//------------Form load Events and functions-----------------------------
DataSet dataset2 = new DataSet();
ClassesAll.PartyandProductClass PartyandProducts = new ClassesAll.PartyandProductClass();
private void productform_Load(object sender, EventArgs e)
{
try
{
// events for loading partytype broker on load
string query2 = "SELECT productNameUR, id FROM product";
SqlCommand command2 = DBConnectivity.getCommandForQuery(query2, connection);
SqlDataAdapter adapter2 = new SqlDataAdapter(command2);
adapter2.Fill(dataset2);
int result = command2.ExecuteNonQuery();
this.cBjins.DisplayMember = "productNameUR";
this.cBjins.ValueMember = "id";
DataRow datarow1 = dataset2.Tables[0].NewRow();
datarow1["productNameUR"] = "Select Product";
dataset2.Tables[0].Rows.InsertAt(datarow1, 0);
this.cBjins.DataSource = dataset2.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Suggest me a solution.

Autocomplete in a ComboBox Using Access 2017

I want to make Autocomplete in a ComboBox using Access 2017. So I used this code... But there are some errors, like:
"The name 'da' does not exist in the current context".
Please help me to fix this error.
private void Autocomplete()
{
string query;
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb");
//opening connection
con.Open();
try
{
//initialize a new instance of sqlcommand
OleDbCommand cmd = new OleDbCommand();
//set a connection used by this instance of sqlcommand
cmd.Connection = con;
//set the sql statement to execute at the data source
cmd.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter();
//set the sql statement or stored procedure to execute at the data source
da.SelectCommand = cmd;
//initialize a new instance of DataTable
DataTable dt = new DataTable();
//add or resfresh rows in the certain range in the datatable to match those in the data source.
da.Fill(dt);
foreach (DataRow r in dt.Rows)
{
//getting all rows in the specific field|Column
var rw = r.Field<string>("IMEI");
//Set the properties of a combobox to make it auto suggest.
comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
//adding all rows into the combobox
comboBox1.AutoCompleteCustomSource.Add(rw);
}
}
catch (Exception ex)
{
//catching error
MessageBox.Show(ex.Message);
}
//release all resources used by the component
da.Dispose();
//clossing connection
con.Close();
}
Your OleDbDataAdapter da = new OleDbDataAdapter(); is within try { } scope and
da.Dispose(); is outside of that scope, try to place this line within try { } scope or move OleDbDataAdapter da = new OleDbDataAdapter(); outside of try { }scope.
Your OleDbDataAdapter is declare inside the try block, it doesn't exist outside of it, hence the error you're seeing.
The query string presented here is empty.
When you deal with OleDb objects, it's common practice to make use
of using blocks, which take care of disposing the disposable objects you create.
What you rally don't want, is to set those controls properties inside a foreach loop.
It is also more efficient to fill the ComboBox AutoCompleteCustomSource using AddRage(), instead of adding objects one by one.
This is how I propose to edit your code:
// You can set these properties in the Form designer
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
// [...]
string query = "SELECT [Some Field] FROM [Some Table] WHERE [Some Condition]";
List<string> data = new List<string>();
try {
using (var con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb"))
{
con.Open();
using (var cmd = new OleDbCommand(query, con))
using (var reader = cmd.ExecuteReader()) {
if (reader.HasRows) {
while (reader.Read()) {
data.Add((string)reader["IMEI"]);
}
}
}
}
}
catch {
// Notify, log, whatever fits
}
comboBox1.AutoCompleteCustomSource.Clear();
comboBox1.AutoCompleteCustomSource.AddRange(data.ToArray());
data.Clear();

display data to listbox C#

Listbox does not show data. Verified data is in database and I am not getting an
error. Not sure where/what is wrong. Thanks in advance. My code is attached.
private void UpDateList()
{
// add data connection and fill data set.
SqlConnection conn = new SqlConnection(dataSource);
DataTable dt = new DataTable();
string sqlString = "select * from Suppliers";
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = sqlString;
da.Fill(ds);
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
foreach(DataRow dRow in ds.Tables[0].Rows)
{
ArrayList values = new ArrayList();
foreach(object value in dRow.ItemArray)
{
values.Add(value);
_Suppliers.Add(values);
}
}
lstSuppliers.DataSource = _Suppliers;
lstSuppliers.Update();
}
It's kinda pointless to enumerate one bindable data collection and transfer data into another bindable collection so it can be bound. Just have your list use the default view of the datatable that already holds the data (allows sorting, filtering etc)
E.g.
LstSuppliers.DataSource = ds.Tables[0].DefaultView;
LstSuppliers.DisplayMember = "column name goes here of what to show eg SupplierName";
LstSuppliers.ValueMember = "column whose value to use for lstSuppliers.SelectedValue e.g. supplierId";
And then for example, not required but an example possibility:
ds.Tables[0].DefaultView.Sort = "[SupplierName] ASC";

How to get the data when I select a datagridview cell or column

I have 2 datagridview controls in a Windows Forms application.
I would like to get the info of a person when I select first datagridview cell or row to next datagridview:
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
adap3 = new SqlDataAdapter(#"SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id='"+DailyGV.CurrentRow+"'", con);
ds3 = new DataSet();
adap3.Fill(ds3, "dailyattendance");
dataGridView1.DataSource = ds3.Tables[0];
}
Im trying the above code. But it's not working.
I'm not too sure what DailyGV.CurrentRow is but basically you can use the RowHeaderMouseClick...see MSDN documentation. To use it, hook an event handler to it when initializing the form components (you can use VS designer as well...
dataGridView1.RowHeaderMouseClick += dataGridView1_RowHeaderMouseClick;
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
}
this event handler will get fired everytime you select a row header in the DataGridView control which will pass information about the event through an instance of the DataGridViewCellMouseEventArgs class (see MSDN documentation). This argument has a RowIndex property that provides the index of the row clicked which you can use to retrieve the values of the cells in that row...including the person id (if provided)...for example...
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
string personId = dataGridView1.Rows[e.RowIndex].Cells["PersonId"].Value;
//TODO: implement your own query to retrieve data for that person id
}
notice that you need to provide a proper column name when access the cells collection indexer...Cells["columnName"]
I will not give any description about the solution because Leo and Arsalan Bhatti has already suggested the solution. I am just telling you how your code should looks like and how it should be written.
string connectionString = consettings.ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
string empID = DailyGV.CurrentRow.Cells["employee_id"].Value.ToString();
SqlCommand Cmd = con.CreateCommand();
Cmd.CommandText = "SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id=#employee_id";
Cmd.Parameters.Add("#employee_id", SqlDbType.Int).Value = Int32.Parse(empID);
adap3 = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
adap3.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch
{}
}
try
{
cn.Open();
string query = "select employee_id,Employee_Name,Image_of_Employee from Employee_Details where employee_id='" + dataGridView1.SelectedCells[0].Value.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
string aa = (string)sdr["employee_id"];
string bb = (string)sdr["employee_name"];
txtEmployeeID.Text = aa.ToString();
txtnameofemployee.Text = bb.ToString();
byte[] img=(byte[])sdr["Image_of_employee"];
MemoryStream ms=new MemoryStream(img);
ms.Seek(0,SeekOrigin.Begin);
pictureBox1.Image=Image.FromStream(ms); cn.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
You are passing the current row's index as employee id in SELECT query. Pass employee id for the selected record. Then it will work fine.

Categories