display data to listbox C# - 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";

Related

Fill combobox with multiple datasets from the same database column at the same time

I have a combobox that is filled from a database conditionally by checking off one of 10 checkboxes. Each of the 10 checkboxes contains the code below, which selects a portion of column based on a value in column2.
private void Check1_CheckedChanged(object sender, EventArgs e)
{
if (Check1.CheckState == CheckState.Checked)
{
// SQL Server connection
SqlConnection conn = new SqlConnection(#"Server = Server; Database = DB; Integrated Security = True");
DataSet ds = new DataSet();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [Column1] FROM [DB].[dbo].[Table1] WHERE [Column2] = 50", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
combo1.DisplayMember = "Column1";
combo1.ValueMember = "ID";
combo1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
//Exception Message
}
finally
{
conn.Close();
conn.Dispose();
}
}
if (Check1.CheckState == CheckState.Unchecked)
{
combo1.DataSource = null;
}
Therefore, it is rather trivial to fill the combobox with each separate condition. What I want to do that I'm not sure of the approach, however, is that when more than one checkbox is checked, the combobox will display the data from every checked checkbox at once (all this data will be from the same column). Moreover, when a single checkbox is then unchecked, I only want it to remove its own dataset from the combobox and not everything.
Is this possible?
I think it's possible if you have 1 dataset and then you dynamically build up your SQL query. Set up a variable for the columns you want to return based on all the selected comboBoxes.
Use 1 method for all your after update event on the comboBoxes to make it easier and more maintainable.
In terms of mapping the dynamics columns to the dropdowns, I don't work with Winform so I'm not sure but hope this can help a bit.
You can use the for loop to iterate the values you have retrieved and append the combo box value. Example:
comboBox.Items.Clear(); // <-- Declare this at initialization of the page or whatever scenario you have
private void Check1_CheckedChanged(object sender, EventArgs e)
{
if (Check1.CheckState == CheckState.Checked)
{
// SQL Server connection
SqlConnection conn = new SqlConnection(#"Server = Server; Database = DB; Integrated Security = True");
DataSet ds = new DataSet();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [Column1] FROM [DB].[dbo].[Table1] WHERE [Column2] = 50", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
// Using loop to iterate the values and append the combo box
for(int i=0;i<da.Rows.Count;i++)
{
combo1.Items.Add(da[i]["Column1"].ToString());
combo1.Items[combo1.Itemx.Count-1].Text=da[i]["Column1"].ToString();
combo1.Items[combo1.Itemx.Count-1].Value=da[i]["Column1"].ToString();
}
}
catch (Exception ex)
{
//Exception Message
}
finally
{
conn.Close();
conn.Dispose();
}
}
if (Check1.CheckState == CheckState.Unchecked)
{
combo1.DataSource = null;
}
This is just an example, hope you can get the idea

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();

How can I get my return value from stored procedure to display on GridView?

I have a return value from the stored procedure GetTeam, and I want it to be displayed in the Gridview. This is what I have, but it is not displaying in the gridview:
protected void getTeam()
{
SqlConnection con;
string CS = Configuration.Manager.ConnectionStrings["TEAM"].ConnectionString;
DataTable dt = new DataTable();
using(con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("GetTeam",con);
SqlDataAdapter da = new SqlAdapter(cmd);
da.fill(dt);
Gridview1.Datasource = dt;
Gridview1.Databind();
}
}
Could anyone help?
Here try this solution below, keep in this solution we are sending a parameter to help narrow our results to specific team.
using (SqlConnection conn = new SqlConnection())
{
//Connection string
conn.ConnectionString = ConnectionString.DataSourceString;
//Create adapter and assign store procedure name
SqlCommand cmmd = new SqlCommand()
{
CommandType = CommandType.StoredProcedure
};
// Assign to Command type
//exception is caught because it cannot find Stored Procedure
//Insert parameters into row from input text
cmmd.CommandText = "GetTeam";
// Send parameter
cmmd.Parameters.AddWithValue("#PGetDayTeam",
ShiftParameterTextBox.Text.Trim());
cmmd.Connection = conn;
try
{
conn.Open();
//If we do not receive any records
GridView2.EmptyDataText = "No Records Found";
GridView2.DataSource = cmmd.ExecuteReader();
GridView2.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close and dispose connection
conn.Close();
conn.Dispose();
}
// select from grid
protected void GridView2_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
GridViewRow row = GridView2.Rows[e.NewSelectedIndex];
string GetTeam = row.Cells[2].Text;
// You can use it in viewstate or what you choose.
ViewState["GetTeam"] = GetTeam;
}
The Fill operation then adds the rows to destination DataTable objects
in the DataSet, creating the DataTable objects if they do not already
exist. When creating DataTable objects, the Fill operation normally
creates only column name metadata. However, if the MissingSchemaAction
property is set to AddWithKey, appropriate primary keys and
constraints are also created.
You're using sql prosedure. So you already have a Colums' name. You don't need to use DataTable. The Sql adapter can fill dataset also. You need to use DataSet first.
public static DataSet ExecuteDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters);
//create the DataAdapter & DataSet
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);
//return the dataset
return ds;
}
Then you can bind your Gridview with that one.
grdView.DataSource = ds;
grdView.DataBind();

retrieve with multi or

im creating wfp application i want to retrieve table to datagridview
with multi value selected in listbox, getting all data that selected from listbox, so the main idea
is apply this query from sql to application
select * from Vwtb where firstname='' or firstaname='' or ..
i have tried with while loop and searched a lot but not worked this is my code please if its something strange for you im not professional :)
string[] orand = { "or"+listBox1.Text };
foreach (string sm in orand)
{
cn.Open();
string select = "select * from productvw where firstname='" + sm + "'";
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable ds = new DataTable();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds;
cn.Close();
}
any type of help will be so appreciated ....
You can convert your array to a string that can be used in IN operator.for achieving that, use this extension method
public static class StaticClass
{
public static string ConvertStringArrayToString(this string[] array)
{
StringBuilder builder = new StringBuilder();
for (int i=0;i<array.Length;i++)
{
builder.Append(array[i]);
if(i+1==array.Length)break;
builder.Append(',');
}
return builder.ToString();
}
}
Then in your code use it like this
string[] orand = { "or"+listBox1.Text };
var values=orand.ConvertStringArrayToString();
cn.Open();
string select =" SELECT * FROM productvw WHERE firstname IN "+"("+values+")"
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable ds = new DataTable();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds;
cn.Close();
You could use the IN operator.
string command = "SELECT * FROM productvw WHERE firstname IN (#names)";
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
dataAdapter.Parameters.Add("#names", names);
The names would be a list of strings, List<string>, and would contain all the first names you want to use.
You can use the following syntax:
SELECT *
FROM productvw
WHERE firstname IN (value1,value2,...);
Start by creating a loop that generates the sql string With the values populated.

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