Fill combobox with database, starting with blank item - c#

I have a combobox that is filled with this db statement:
select ' ' as usr_entrada, null as No_Servicio union select usr_entrada, No_Servicio from Telemarketing where Id_Sucursal='cordoba'
Here the combobox is filled with a blank item before the true data, and the statement works perfectly, this is the result:
+--------------+-------------+
| usr_entrada | No_Servicio |
+--------------+-------------+
| | NULL |
+--------------+-------------+
| CAPTURA-TMK | No_Servicio |
+--------------+-------------+
| SUP | No_Servicio |
+--------------+-------------+
| TCA02TMK | No_Servicio |
+--------------+-------------+
| TCACONTABAUX | No_Servicio |
+--------------+-------------+
| TMKCBA01 | No_Servicio |
+--------------+-------------+`
The issue is that, when I fill the combobox, for some reason it erases the blank item, and I don't understand why. This is my method to fill the combobox:
void llenaUsuarios()
{
Conexion con = new Conexion();
DataTable dt=new DataTable();
using (con.getcon())
{
const string sql = "select ' ' as usr_entrada, null as no_servicio union select usr_entrada, No_Servicio from Telemarketing where Id_Sucursal=#Sucursal";
using(SqlCommand cmd=new SqlCommand(sql, con.getcon()))
{
SqlDataReader rd;
cmd.Parameters.AddWithValue("#Sucursal", cveSucursal);
rd = cmd.ExecuteReader();
if (rd.HasRows)
{
rd.Read();
dt.Load(rd);
comboBox1.DisplayMember = "usr_entrada";
comboBox1.ValueMember = "no_servicio";
comboBox1.DataSource = dt;
}
}
}
}
Can anyone tell me what am I doing wrong? The sql statement is not the problem, I have another combobox filled that way and it works just fine.
Thank you for your time :-)

So you want to insert a blank item in the combo box at index = 0, correct?
//rest of your code
comboBox1.DataSource = dt;
comboBox1.Items.Insert(0, new ListItem(" ", "-1")); //After filling the DataSource, insert an item in the Combobox at Index 0
What I have done here is to insert an item after the datasource is filled with the data from the DB. What happening in your code seems obvious to me. For more info on this, have a quick read. The article shows in Windows Forms but you'll get the idea in case you are on asp.net
Adding and Removing Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control
Last time I worked on these controls was almost a decade ago. I'm typing a sample here in SO, taking a reference from my old Source Control repo.
Common Variables
DataRow rw;
public DataSet ds = new DataSet();
public SqlDataReader dr;
public SqlCommand cmd = new SqlCommand();
public SqlDataAdapter adp = new SqlDataAdapter();
Using DataTable
//If DataSet contains the table already, remove it first
if (ds.Tables.Contains(tbl))
ds.Tables.Remove(tbl);
//Open connection here. Better with using
cmd.CommandText = "YOUR_SQL_QUERY_GOES_HERE";
adp.SelectCommand = cmd;
adp.Fill(ds, tbl);
//close the connection here
rw = ds.Tables[tbl].NewRow(); //Add a new row
rw[0] = "-1"; //Set it's value
rw[1] = "Itemtext"; //Set it's text
ds.Tables[tbl].Rows.InsertAt(rw, 0); //Insert this row in the DataTable(DT) at Index 0
comboBox1.DataSource = ds.Tables[tbl]; //Assign the DT in the DataSource of the combobox
comboBox1.DataTextField = "Default Text";
comboBox1.DataValueField = "Default Value";
comboBox1.DataBind();
Using DataReader
comboBox1.Items.Clear(); //Clear the dropdown first
//Open the connection, set SqlCommandType and Text
using (SqlDataReader reader = sqlcmd.ExecuteReader())
{
comboBox1.DataSource = reader; //Assign DataReader to the DataSource of the Combobox
comboBox1.DataValueField = "usr_entrada";
comboBox1.DataTextField = "no_servicio";
comboBox1.DataBind();
//Here you can insert a new item at Index 0 of the Combobox.
//For your case, keep the "Default Text" blank
comboBox1.Items.Insert(0, new ListItem("--Default Text--", "-1"));
}
//close the connection
Please note that the code is not optimized for production use and is only to give you more ideas! So do not penalize the answer because of the code quality. I have written it directly in SO and there might be some syntax errors!

Related

Set SelectedValue in combobox that populated from Data Table in c#?

I have a Combobox in my form. This Combobox is populated with values from a table(Faculty) in the database.
I need to set the SelectedValue of this Combobox based on the record in another table(student). Both tables are in the same database.
I tried to set SelectedValue using the value getting from student table
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
but it didn't work.
So far I was only able to populate the Combobox ,
// --- populate faculty cmb ---
MySqlCommand cmdCmb = new MySqlCommand("SELECT facultyname FROM faculty;", db.getConnection());
db.openConnection(); // open connection
using (var reader = cmdCmb.ExecuteReader())
{
while (reader.Read())
{
cmbfaculty.Items.Add(reader.GetString("facultyname"));
}
}
but unable to set SelectedValue.
string sQuery = "SELECT indexno,faculty FROM student WHERE indexno ='"+selected+"'";
MySqlCommand cmd = new MySqlCommand(sQuery, db.getConnection());
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);
txtindex.Text = table.Rows[0][0].ToString();
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
Hoping to fix the issue.
EDIT:
Able to do that by finding the item that exactly matches the specified
string ComboBox.FindStringExact Method,
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
needed to be replaced with
cmbfaculty.SelectedIndex = cmbfaculty.FindStringExact(table.Rows[0][1].ToString()) ;
Are there any other ways to archieve this.
Able to do that by finding the item that exactly matches the specified string ComboBox.FindStringExact Method,
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
needed to be replaced with
cmbfaculty.SelectedIndex = cmbfaculty.FindStringExact(table.Rows[0][1].ToString()) ;

Replace values from Select query in SQL using C#

My SQL query is:
GridView1.DataSource = GetData();
GridView1.DataBind();
DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["OfficeConnection"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Consulting ", con))
{
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);
}
}
return dt;
}
I have a table with a few columns and what I am trying to achieve is to display the data in a GridView. At the moment the data is displayed in my GridView but I would like to replace text in the columns and then display in the gridview
So for example this is my table:
| DisplayName | $_License
+-------------+------------------------
| User 1 | TestLicense:License1 |
| User 2 | TestLicense:License2 |
So in my Gridview I would to display:
| Display Name | License Type |
+--------------+------------------------+
| User 1 | License1 |
| User 2 | License2 |
Note that theDisplay Name has a space and the $_License is changed to License Type and the row is changed from TestLicense:License1 to License1
Any help will be greatly appreciated.
Use this query:
"SELECT DisplayName 'Display Name', Replace($_License,'TestLicense:', '') 'License Type' Name FROM Consulting "
Modify your select query as per required result:
SELECT DisplayName AS 'Display Name' , RIGHT($_License, LEN($_License) - 11) AS 'License Type' FROM Consulting;

Error adding from database to dropdownlist

I have a panel that is visible only when the Edit button from GridView is clicked.
In that panel is a form with a DropDownList and a TextBox where you can write a number and add it to a ListBox.
After all the numbers wanted are added to the ListBox when I click the button Finalize is adding to the database the data. In Gridview I have the name concatenate from database , because I have Lastname and Firstname separately.
To be more easy I chose to add from database in DropDownList when I click on Edit button with the specific ID.
When Edit button is clicked this error is showing:
Operation is not valid due to the current state of the object.
In the line where I add in DropDownList. I verified the names of my database, of my table , all and is correct. I even tried only with firstname , not concatenate and it does the same error. I don't know what is wrong. I hope you can help me. This is the code where the error appears.
protected void btnEditSO_Click(object sender, EventArgs e)
{
panelSO.Visible = true;
btnFinalizeSO.Text = " Update ";
Button but = (Button)sender;
GridViewRow grid = (GridViewRow)but.NamingContainer;
string select_sql_SOddl = "SELECT ID, (LASTNAMER | | ' ' | | FIRSTNAMER ) AS REFERENTNAME FROM REFERENT_SHIPPING WHERE ID=" + grid.Cells[14].Text;
using (OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
{
con.Open();
OracleCommand cmd1 = new OracleCommand(select_sql_SOddl, con);
OracleDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
ddlReferentShip.Items.Add(dr[0].ToString());
// ddlReferentShip.Items.Add(dr["REFERENTNAME"].ToString());
// ddlReferentShip.DataSource = dr1;
// ddlReferentShip.DataTextField = dr1["REFERENTNAME"].ToString();
// ddlReferentShip.DataValueField = dr1["ID"].ToString();
// ddlReferentShip.DataBind();
}
}
}
You are checking dr1.Read()
and reading dr[0].Tostring()
Also try to clear the list before adding the data. Then the index should be 1 if you need to show the name
it should be
while (dr1.Read())
{
ddlReferentShip.Items.Add(dr1[1].ToString());
}
I guess ID is numeric in query you are passing as .Text
try this
string select_sql_SOddl = "SELECT ID, (LASTNAMER | | ' ' | | FIRSTNAMER ) AS REFERENTNAME
FROM REFERENT_SHIPPING WHERE ID=" + Convert.ToInt32(grid.Cells[14].Text);
also all ways try to use parameterized query to avoide SQL INJECTION
Why you set ddl item from dr when you have dr1 as datareader.
Maybe you can try this:
protected void btnEditSO_Click(object sender, EventArgs e)
{
panelSO.Visible = true;
btnFinalizeSO.Text = " Update ";
Button but = (Button)sender;
GridViewRow grid = (GridViewRow)but.NamingContainer;
string select_sql_SOddl = "SELECT ID, (LASTNAMER | | ' ' | | FIRSTNAMER ) AS REFERENTNAME FROM REFERENT_SHIPPING WHERE ID=" + grid.Cells[14].Text;
using (OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
{
con.Open();
OracleCommand cmd = new OracleCommand(select_sql_SO, con);
OracleCommand cmd1 = new OracleCommand(select_sql_SOddl, con);
OracleDataReader dr = cmd.ExecuteReader();
OracleDataReader dr1 = cmd1.ExecuteReader();
int i=0;
while (dr1.Read())
{
ddlReferentShip.Items.Add(dr1[1].ToString());
i++;
// ddlReferentShip.Items.Add(dr["REFERENTNAME"].ToString());
// ddlReferentShip.DataSource = dr1;
// ddlReferentShip.DataTextField = dr1["REFERENTNAME"].ToString();
// ddlReferentShip.DataValueField = dr1["ID"].ToString();
// ddlReferentShip.DataBind();
}
}
}

Can't figure out why my results are appearing with ListBox{"name"}

public void loadAllEmployeesFromSQLServer()
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
conn.ConnectionString = "Server=WIN2008SERVER;Database=Kiosk;Uid=kiosk;Pwd=kiosk;";
conn.Open();
string query = "SELECT [displayName],[activeDirectoryName],[roleID],[activeAccount] FROM [ProbationKiosk].[dbo].[Employees]";
cmd.Connection = conn;
cmd.CommandText = query;
SqlDataReader dr = cmd.ExecuteReader();
ArrayList allEmployees = new ArrayList();
while (dr.Read())
{
employees emp = new employees(dr["displayName"].ToString(), dr["activeDirectoryName"].ToString(), dr["roleID"].ToString(), Int32.Parse(dr["activeAccount"].ToString()));
allEmployees.Add(emp);
string[] employeeData = new string[3];
employeeData[0] = emp.commonName;
employeeData[1] = emp.activeDirectory;
employeeData[2] = emp.currentRole;
ListViewItem lvi = new ListViewItem(employeeData);
if (emp.isActive == 1)
{
checkedListBox1.Items.Add(lvi, true);
}
else
{
checkedListBox1.Items.Add(lvi, false);
}
}
}
I made my CheckedListBox a multicolumn table.
I debugged my code and I am getting the data stored into ListViewItem
but when it's being displayed to the UI, it appears as
"ListViewItem {"name..."}"
instead of
"[ ] | First Name Last Name | active directory name | roleID"
You're seeing that because when you execute the following line:
checkedListBox1.Items.Add(lvi, true);
It's implicitly calling lvi.ToString(), which is displaying the name of the class.
Try this instead:
checkedListBox1.Items.Add(string.Join(" | ",
lvi.SubItems.Cast<ListViewItem.ListViewSubItem>().Select(x => x.Text)));
Also, I assume you're setting the MultiColumn property on the CheckedListBox to true. That does not lay things out nicely formatted, like in a grid. It just determines whether or not items display in a single column or flow into multiple columns as space permits.
MultiColumn = false:
MultiColumn = true:
You might be able to attain a quasi-table layout by using tabs, but it may look funny if some strings are much longer than the rest.
checkedListBox1.Items.Add(string.Join("\t",
lvi.SubItems.Cast<ListViewItem.ListViewSubItem>().Select(x => x.Text)));
You could probably get around that by finding the longest probable string and padding the Text property accordingly:
checkedListBox1.Items.Add(string.Join("",
lvi.SubItems.Cast<ListViewItem.ListViewSubItem>()
.Select(x => x.Text.Padding(20, ' ')));

How to retrieve data from a table row by row?

I have a table in sql server database as shown below,
id | Labels
-----+----------------
1 | MyHeaderLabel
2 | MyFooterLabel
3 | MyDescirption
Label1.text = firstrow(MyHeaderLabel)
Label2.text = secondrow(MyFooterLabel)
is there anyway to achieve it like this.
I am going to use stored procedure to retrieve them. Should I use data reader to get these value
Yes, DataReader is a good option.
using(SqlConnection conn = new SqlConnection(YourConnectionStringHere))
{
SqlCommand cmd = new SqlCommand(YourSQLQuery, conn);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
Label1.Text = dr[1].ToString();
// This is just an example. You can do whatever you want. :)
}
}
I maybe wrong. So, feel free to correct me. ;)
Hey i solved my question
It takes the rows in order
Label1.Text = (dr.Read()) ? dr["Promts"].ToString() : "";
Label2.Text = (dr.Read()) ? dr["Promts"].ToString() : "";
Thanks guys
Try this,
using(SqlConnection cn = new SqlConnection("connection_string"))
{
cn.Open();
using(SqlDataAdapter adapter = new SqlDataAdapter("selest * from table_name",cn))
{
DataTable table = new DataTable();
adapter.Fill(table);
foreach(DataRow row in table.Rows)
{
//get column data for a row using row["column_name"].ToString()
}
}
}

Categories