How to fill combobox with database values with method from DAL - c#

I have a table called Departments where the column i wish to populate my combobox with is named DeptId. below is the datatable i created in my DAL class, but i cant for my life figure out how to put these values into deptCombobox in my form1 class. I am trying to attach it to a button named refreshButton_Click, but nothing works no matter what i try
//DAL
public DataTable fillDeptCombo()
{
SqlConnection con = new SqlConnection(#"Data Source=");
con.Open();
string queryText = "SELECT * FROM DEPARTMENT ";
SqlCommand cmd = new SqlCommand(queryText, con);
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
//controller
public DataTable fillDeptCombo()
{
return dal.fillDeptCombo();
}
Any help would be greatly appreciated

You have mentioned "form1", I assume it is for windows forms.
In your form1 cs code, this should do it.
DAL dl=new DAL()
Datatable dt=DAL.fillDeptCombo()
combobox.datasource=dt;
combobox.valuemember="deptID" //replace this with your value
combobox.displayMember="DeptName" //replace this with your text

Related

How to fill combobox with database values using n tier architecture in c# windows form

i write the code to fill combobox with database value. my code is working correctly if this code written on presentation layer. But i want to written this code on data layer. i have 3 project in my solution (UI, BLL, DAL). i want this code in DAL and then call in UI with the help of BLL. how to do that. please help me. here is my code.
How to convert my code into 3 tier architecture.
using (SQLiteConnection conn = new SQLiteConnection(EmployeeComboFills.ecbconn()))
{
string CommandText = "SELECT Name FROM User";
using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
CELD_employeename.Items.Add(dr["Name"].ToString());
}
}
}
how to write this code in 3 tier. OR if someone have better code for do that then please share it. Thanks.
Instead of adding the items to the combobox directly, add them to a list. Assuming that EmployeeComboFills is your static DAL class, you can add this method to it
public static List<string> GetUserNames()
{
string CommandText = "SELECT Name FROM User ORDER BY Name";
using (SQLiteConnection conn = new SQLiteConnection(ecbconn()))
using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
{
conn.Open();
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
return dt.Rows
.Cast<DataRow>()
.Select(dr => dr["Name"].ToString())
.ToList();
}
}
Then you can assign it to the combobox with
CELD_employeename.DataSource = EmployeeComboFills.GetUserNames();

Combo Box Databinding in WPF

I have a combobox in a wpf form. I would like to bind it to a table in MS SQL server. However each time i run my code i keep on running into errors. Any assistance would be appreciated. Below is my code:
private void OnLoad(object sender, RoutedEventArgs e)
{
FillComboBox();
}
protected void FillComboBox()
{
SqlConnection con = new SqlConnection(cs);
DataSet ds = new DataSet();
try
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT RegNumber,Make FROM Vehicles GROUP BY RegNumber,Make", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
combovehicle.DisplayMemberPath = "RegNumber";
combovehicle.SelectedValue= "Make";
combovehicle.DataContext = ds.Tables[0];
}
catch(Exception)
{
}
}
}
}
combovehicle.DisplayMemberPath = "RegNumber";
combovehicle.SelectedValue= "Make";
combovehicle.DataContext = ds.Tables[0];
So you told WPF to display using the property Make and RegNumber
but you passed in a DataTable object
DataRow does provide indexer for accessing the property but it does NOT contain those properties. Plus DataTable is not IEnumerable so you can't really use it as data source.
AND most importantly you are doing it all wrong. You should almost never make database call directly in your view and set the data source to the output table. You should do this thru MVVM pattern.

Populate Devexpress GridView using a DataAdapter and SqlCommand in code

I have a little problem with populating my DevExpress Gridview, I want to have a two level gridview and using SqlCommand. At first I created a Dataset and added two tables and also defined relation for them. But it does not work. Can you help me find my problem?
Here is my code
string owner = "SELECT [OBJECTID],[Name] ,[Family] ,[Father] ,[Dftarche] ,[Birthday] ,[education] ,[home_address] ,[farm_address] ,[ensurance] ,[phone] ,[home_number] ,[owner_id] FROM [dbo].[OWNER]";
string property = "SELECT [number] ,[owner_ID] ,[GPSId] ,[Energy],[corp_type] ,[Pool],[irrigation] ,[variety] ,[trees] ,[utilizat] ,[address] ,[water_hour] ,[w_source] ,[w_inche],[w_dore],[NoeMalekiat],[MotevasetBardasht],[Area] ,[OBJECTID],[Shape] FROM [dbo].[Property] ";
string strConnString = Properties.Settings.Default.land_gisConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand command = new SqlCommand(owner, con);
SqlDataAdapter adapter = new SqlDataAdapter();
System.Data.DataSet dsMain = new System.Data.DataSet();
adapter.SelectCommand = command;
adapter.Fill(dsMain, "First Table");
adapter.SelectCommand.CommandText = property;
adapter.Fill(dsMain, "Second Table");
dsMain.Tables.Add(iFeatureSet.DataTable.Copy());
adapter.Dispose();
command.Dispose();
DataRelation newRelation = new DataRelation("املاک شخصی", dsMain.Tables["First Table"].Columns["owner_id"], dsMain.Tables["Second Table"].Columns["owner_ID"]);
dsMain.Relations.Add(newRelation);
GridAttrebuteTable.DataSource = dsMain.Tables[2];
// gridView5.DataSource = dsMain.Tables[1];
dataGridView1.DataSource = dsMain;
I searched and found this http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx and it seems my code is right but it does not show anything in grids
Thank you very much for your help
I Could figure out how to fix it.It works fine now(Above Code is edited) but now If I add a new DataTable I do not know why it does not work again
You need a new GridView for each detail table. You can't display both a master and detail in the same GridView.
Try this example

Retrieve records from Mysql database and display it in a combo box

I have a DbConnect class which queries a MySQL database and store the results into a datatable - something like this:
public DataTable selectCombo()
{
string query = "SELECT DISTINCT month FROM printer_count";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
this.CloseConnection();
return dt;
}
Now how to retrieve the datatable from the class into the combo box main form? Can I do something like this?
ComboBox1.DataSource = dbConnect();
ComboBox1.DisplayMember = "Name"; // column name to display
You have two variables with the same name. (dt) One is defined as a string, the other one inside the if block is defined as a datatable. You return the empty string and this, of course, cannot work when you try to assign the DataSource of the combo
public DataTable selectCombo()
{
DataTable dt = new DataTable();
string query = "SELECT DISTINCT month FROM printer_count";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
this.CloseConnection();
return dt;
}
Now you could write
....
ComboBox1.DisplayMember = "Name";
ComboBox1.DataSource = selectCombo();
.....
Also this code is not very safe. If, for any reason, you get an exception, the CloseConnection will not be called leaving an open connection around and this is very problematic for the stability of your system. However, fixing that problem, requires a different approach to you OpenConnection code. Instead of true this method should return the MySqlConnection object so your calling code could apply the using statement around the connection instance

Fill ComboBox with Access DB data

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;

Categories