Add "ALL" option as 1st Selection Of Combobox - c#

I am in need of adding in the ALL option as the top choice of a combobox. I have tried this code below, but All is not addded, what must I alter in order to have that added?
string query = "select [empname] from [server].[dbo].[table]";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "tables");
cbotables.DisplayMember = "empname";
cbotables.Items.Insert(0, "All");
cbotables.DataSource = ds.Tables["tables"];
EDIT
I just realized a few things were not showing in my code...my connection string is declared above, and the contents of the combobox display as they should from the database, just no ALL option added.

Perhaps the simplest way would be to Insert a row into the DataTable assuming its only role is to be a DataSource:
// fill the datatable
dt.Load(cmd.ExecuteReader());
var dr = dt.NewRow();
dr["Id"] = -1;
dr["Name"] = "All";
dt.Rows.InsertAt(dr, 0);
cboEmp.DisplayMember = "Name";
cboEmp.ValueMember = "Id";
cboEmp.DataSource = dt;
It is more common to have a ValueMember with these so you can tell what was selected, thus the "Id" column. If the DataTable has other purposes you may not want to add fake data to it. For that, you could transfer the data to an anonymous list:
dt.Load(cmd.ExecuteReader());
// xfer data to anon collection
var myDS = dt.AsEnumerable()
.Select(q => new {Name = q.Field<String>("Name"),
Value = q.Field<Int32>("Id") }
)
.ToList();
// add ALL with fake id
myDS.Insert(0, new { Name = "ALL", Value = -1 });
cboEmp.DisplayMember = "Name";
cboEmp.ValueMember = "Value";
cboEmp.DataSource = myDS;
Either way gets the same results:
If you truly dont need the Id, you dont need an anon type and can just select the name and a List<string>

Related

C# DropDownList listing number value

I have a dropdownlist that fills like:
cmd.CommandText = "select * from dbo.pelischool";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataTextField = ds.Tables[0].Columns["schoolName"].ToString();
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataBind();
Now I want to read the listing number of the selected item(in order to place it in a query).
So, while my dropdownlist has values like "Oxford University", "MIT University", "Simon Fraser University" etc, I want clicking an item from the list, store the value of this item in the list. To be more specific, if clicking the first item, then
int number = 1. if clicking the second item, then
int number = 2.
Is it possible to be done with something like:
DropDownList1.SelectedItem.????;
Thank you for your time!
You didn't bind item's value to dropdownlist, so you need to bind it.
like this
DropDownList1.DataValueField = ds.Tables[0].Columns["Column name that contain the value of Item"].ToString();
and then you can use to get it's value like as follow
string item_value = DropDownList1.SelectedValue;
If you want selected Value then use
DropDownList1.SelectedValue
and if you want selected item then use
DropDownList1.SelectedItem
In addition to Nitin Kumar answer, selected item text can be obtained by:
var selectedText = DropDownList1.SelectedItem.Text;
Selected Value
var selectedValue = DropDownList1.SelectedValue;
cmd.CommandText = "select * from dbo.pelischool";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataTextField = ds.Tables[0].Columns["schoolName"].ToString();
DropDownList1.DataValueField = ds.Tables[0].Columns["SomeValueColumn or id column"];
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataBind();
and then you can use...
string id = DropDownList1.SelectedValue.ToString();
Try this.
cmd.CommandText = "select id,schoolName from dbo.pelischool";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt );
if (dt != null)
{
if (dt.Rows.Count > 0)
{
ddlPosition.DataSource = dt;
ddlPosition.DataTextField = "schoolName";
ddlPosition.DataValueField = "Id";
ddlPosition.DataBind();
}
}

DataSet Select Column

I would like to select a specific column from a Dataset once it's been populated (e.g. Column Grades) and put the values into a list
string excelFile = #"C:\Scores.xlsx";
if (File.Exists(excelFile))
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+excelFile+";Extended Properties=Excel 12.0;";
var dataAdapter = new OleDbDataAdapter();
var objConn = new OleDbConnection(connString);
//SELECT [Name],[Grade],[Location] ect...
const string query = "SELECT * FROM [TeamScores$]";
var objCmd = new OleDbCommand(query, objConn);
var table = new DataSet();
dataAdapter.SelectCommand = objCmd;
dataAdapter.Fill(table);
//I would like to filter the DataSet to select only [Name] and populate the values into a List<string>
dataGridView1.DataSource = table.Tables[0]; //Will show all results
}
Your variable naming is confusing you.
var table = new DataSet(); // not good at all
A DataSet is not a table. A DataSet contains DataTables.
Try:
DataSet ScoresDataSet = new DataSet();
Then you can use the Select method on the table (something like...):
DataTable ScoresTable = ScoresDataSet.Tables[0];
dataGridView1.DataSource = ScoresTable.Select("Your criteria");
I have now solved the issue I can change "Grade" to which ever column I wish and it'll show the values associated.
DataTable scoresTable = ScoresDataSet.Tables[0];
var result = scoresTable.AsEnumerable()
.Select(r => r.Field<string>("Grade")).Where(r => r != null);
var listOfGrades = result.ToList();
You need adjust this line:
dataGridView1.DataSource = table.Tables[0]; //Will show all results
for example this one:
dataGridView1.DataSource = table.Tables[0].Select("yourField=5")); // you filter the datarows where yourField is 5.
or
dataGridView1.DataSource = table.Tables[0].Select("yourField>5 and yourField<21")); // is another example
Hopefully this can help you :
System.Data.DataSet dsTemp2 = new System.Data.DataSet();
if (dsTemp2.Tables[0].Rows.Count <= 0)
MessageBox.Show("Records not found");
else
{
foreach (DataRow dRow in dsTemp2.Tables[0].Rows)
{
yourtextbox1.Text = dsTemp2.Tables[0].Rows[0][4].ToString();
yourtextbox2.Text = dsTemp2.Tables[0].Rows[0][5].ToString();
yourtextbox3.Text = dsTemp2.Tables[0].Rows[0][7].ToString();
}
}

Put "ALL" on ComboBox[0] so that we filter it. NOTE: ComboBox has data from DB

For example, I have a Combo box with these contents coming from the database using SqlCommand, SqlDataAdapter and DataTable:
Japan
UK
USA
Philippines
Now, I want to add another choices. It should look like this:
----ALL----
Japan
UK
USA
Philippines
If I chose Japan, it will filter and show all the landmarks in the country like Mt. Fuji, Tokyo Tower.
If I chose UK, it will filter and show Big Ben, Westminster, Olympic Stadium.
If I chose USA, it will show fat people, Kim Kardashian.
IF I CHOSE ----ALL----, IT WILL SHOW ALL THE LANDMARKS FROM ALL COUNTRIES.
How do I do this? I'm using C# & SQL Server.
EDIT:
This is how I fill a combo box.
_con.Open();
SqlCommand _viewLandmarks = new SqlCommand("dbo.SelectDevices_AddingForm", _con);
_viewDevices.CommandType = CommandType.StoredProcedure;
_viewDevices.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(_viewLandmarks);
DataTable dTable = new DataTable("LANDMARK");
da.Fill(dTable);
comboModel.DataSource = dTable;
comboModel.DisplayMember = "Landmark";
comboModel.ValueMember = "LandmarkID";
_con.Close();
As said in comments it is just a matter to add a fake record in your returned datatable
_con.Open();
SqlCommand _viewLandmarks = new SqlCommand("dbo.SelectDevices_AddingForm", _con);
_viewDevices.CommandType = CommandType.StoredProcedure;
_viewDevices.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(_viewLandmarks);
DataTable dTable = new DataTable("LANDMARK");
da.Fill(dTable);
DataRow fakeRow = dTable.NewRow();
fakeRow["Landmark"] = "(ALL)";
fakeRow["LandmarkID"] = -1;
dTable.Rows.Add(fakeRow);
comboModel.DataSource = dTable;
comboModel.DisplayMember = "Landmark";
comboModel.ValueMember = "LandmarkID";
_con.Close();
I have added the open/close parenthesys around ALL to to force the new added row to the beginning of your datatable (assuming that it is sorted by Landmark).
Notice also that this approach assumes also that your fields are all NULLABLE. If one or more fields doesn't allow null values you need to set an appropriate value before adding the fakeRow to the Datatale rows collection
Just add a row in your datatable before binding and set the value to All.
Below is a example of binding the combo box
private void BindCombo()
{
DataTable dataTable = GetDataTable();
DataRow row = dataTable.NewRow();
row["Value"] = "0";
row["Name"] = "All";
dataTable.Rows.InsertAt(row, 0);
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Value";
comboBox1.DataSource = dataTable;
}

Filling of ComboBox with Dataset

When am trying to fill Combobox
con.Open();
da = new SqlDataAdapter("Mt_Post_select",con);
//Mt_Post is Stored procedure with Select Command
ds1 = new DataSet();
da.Fill(ds1, "Mt_Post");
// The table has only one row
comboBox1.DataSource = ds1.Tables[0];
comboBox1.DisplayMember = "Mt_Post";
It bind But shows instead of data it having System.Data.DataRowView
What is the wrong this code Please anyone tell me
Replace Mt_Post in comboBox1.DisplayMember = "Mt_Post"; with the name of column whose value you would like to display.
I hope the following sample helps;
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Email");
dt.AcceptChanges();
DataRow dr0 = dt.NewRow();
dr0[0] = "Kadir Sumerkent";
dr0[1] = "kadir#sumerkent.com";
DataRow dr1 = dt.NewRow();
dr1[0] = "Kadir Sumerkent 2";
dr1[1] = "kadir#sumerkent2.com";
dt.Rows.Add(dr0);
dt.Rows.Add(dr1);
dt.AcceptChanges();
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Email";
comboBox1.DataSource = dt;
Let's try this:
Suppose your Stored Procedure is like the code below:
SELECT
Users.User_name AS username
Users.User_Code AS userID
FROM Users
-- WHERE CONDITONS ARE APPLIED
Now in order to Fetch this DataSet you are going to do as follows:
// YOUR OWN CODE
con.Open();
da = new SqlDataAdapter("Mt_Post_select",con);
//Mt_Post is Stored procedure with Select Command
ds1 = new DataSet();
// JUST FILL THE DataSet in THIS WAY
da.Fill(ds1);
// JUST TO MAKE SURE WE HAVE AN EMPTY COMBOBOX
comboBox1.Items.Clear();
comboBox1.DataSource = null;
// NOW POPULATE comboBox1 LIKE THIS
if (ds.Tables[0].Rows.Count > 0)
{
comboBox1.DataSource = ds1.Tables[0];
comboBox1.DisplayMember = "username";
comboBox1.ValueMember = "userID"
}

Duplicate column in DataTable when adding row

I create a DataTable and bind it to a DataGrid. My DataSource consist of one Table (FooTable) which consist of one column (FooName).
The following codes runs fine - except that each time I add a new row, there is a duplicate Column fill in with the same data, which I don't know how to get rid of. See below image and code. I have only one FooName column and a duplicate column comes out.
/* Create a DataGrid dg1 */
DataGrid dg1 = new DataGrid();
DataGridTextColumn col = new DataGridTextColumn();
col = new DataGridTextColumn();
colA.Binding = new Binding("FooName");
colA.Header = "FooName";
dg1.Columns.Add(colA);
dataGrid1.Children.Add(dg1);
/* Create a DataTable and bind it to DataGrid */
SqlCeDataAdapter da = new SqlCeDataAdapter();
string sqlStr = #"SELECT * FROM FooTable";
da.SelectCommand = new SqlCeCommand(sqlStr, conn);
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];
DataRow newRow = dt.NewRow();
newRow["FooName"] = "Donkey";
dt.Rows.Add(newRow);
dg1.ItemsSource = ds.Tables[0].DefaultView;
try setting AutoGenerateColumns to false
dg1.AutoGenerateColumns = false
Try
dg1.AutoGenerateColumns = false;
Should do the work for you. For now the datagrid automatically generates the columns AND adds the one you asked

Categories