How to display two different columns in one combobox - c#

I want to display the two different columns in one particular combobox. When I run it the Customer ID will display. Here is my code.
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname
+ ',' + lastname FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "Customer.firstname, Customer.lastname";
cboName.ValueMember = "Customer.CustomerID";
}

I see you already are creating a single result column containing the "combined" value. That's have the battle.
But, you need to give your column a name (notice the AS FullName alias):
cmd.CommandText = "SELECT CustomerID, firstname + ',' + lastname AS FullName " +
"FROM Customer";
So you can reference it later by name:
cboName.DisplayMember = "FullName";

This will work. I find that binding a Dictionary to a ComboBox has much more predictable results.
My approach omits the extra SQL syntax, DataSet, and SqlDataAdapter.
Instead I use the SqlDataReader to place the desired information into a Dictionary and then I bind that Dictionary as the DataSource of the Combobox.
void GetRecords2()
{
Dictionary <int, string> myDict = new Dictionary<int, string>();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname, lastname FROM Customer";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
myDict.Add(Convert.ToInt32(reader["CustomerID"]),
reader["firstname"].ToString() + " " + reader["lastname"].ToString());
}
if (myDict.Count > 0)
{
cboName.DataSource = new BindingSource(myDict, null);
cboName.DisplayMember = "Value";
cboName.ValueMember = "Key";
}
}

Check this:
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname
+ ',' + lastname FullName FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "FullName";
cboName.ValueMember = "CustomerID";
}
To get selected value :
string customerid = cboName.SelectedValue.toString(); //CustomerID: 1
To get selected item
string fullname = cboName.SelectedItem.Text; //FullName : John Hawkins
Best Regards

Related

Add referenced name instead of ID from comobox

I have 2 tables. First has column (categoryID) that is foreign key for categoryID in second table.Second table has 2 columns (categoryID, categoryName). After bit struggling I've displayed in combobox categoryName instead of categoryID. But now when I want to choose from existing categoryName that is already created (displayed in dropdown in combobox), is not possible because I have to type there int not string format. I'm beginner in programming
con.Open();
string cmddt = "insert into wallettbl(sum, date, categoryID, type)
values ('" + textBox1.Text + "','" + textBox2.Text + "','" +
comboBox1.Text + "', '" + type + "')";
SqlCommand com = new SqlCommand(cmddt, con);
com.ExecuteNonQuery();
How to write code if I want to add string (from combobox) instead of int, but in first table will be added categoryID which is referenced to categoryName.
EDIT: added code for combobox
con.Open();
string cmddt = "select categoryNAME from categoryTbl";
SqlCommand com = new SqlCommand(cmddt, con);
SqlDataAdapter da = new SqlDataAdapter(cmddt, con);
DataSet ds = new DataSet();
da.Fill(ds);
com.ExecuteNonQuery();
con.Close();
change the query to load the categories as below:
string cmddt = "select categoryID, categoryNAME from categoryTbl";
Set the datasource for comboBox1 as below:
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "categoryNAME";
comboBox1.ValueMember = "categoryID";
and finally modify the code to insert data into the wallettbl as follows:
string cmddt=
#"INSERT INTO WALLETTBL(sum, date, categoryID, type)
VALUES (#Sum, #Date, #CategoryId, #Type);";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(insertQuery, conn))
{
cmd.Parameters.Add("#Sum", SqlDbType.Int).Value = textBox1.Text;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = textBox2.Text;
cmd.Parameters.Add("#CategoryId", SqlDbType.Int).Value = Convert.ToInt32(comboBox1.SelectedValue);
cmd.Parameters.Add("#Type", SqlDbType.Varchar).Value = type;
await conn.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}

Using Drop-down with Check-boxes in Asp.net

I have 2 drop-down boxes and i want the first drop-down to filter the 2nd one like cascading so the first one has check-boxes and i want to pass the selected items from the first one to the 2nd but getting a "syntax error". I run it into debug mode and the output result looks like this
CommandText "select id, name FROM myTable where id in (''CKU019','CW5036'') "
and it seems there is extra apostrophe near CKU019. Here is my code
protected void bindDDL()
{
string selectedValues = string.Empty;
foreach (ListItem item in ddchkCountry.Items)
{
if (item.Selected)
selectedValues += "'" + item.Value + "',";
}
if (selectedValues != string.Empty)
selectedValues = selectedValues.Remove(selectedValues.Length - 1);
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand cmd = new SqlCommand("select id, name FROM myTable where id in ('" + selectedValues + "')", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
facDDL.DataSource = ds;
facDDL.DataTextField = "name";
facDDL.DataValueField = "id";
facDDL.DataBind();
}
Remove the extra ' wrapping your selected values...
SqlCommand cmd = new SqlCommand("select id, name FROM myTable where id in (" + selectedValues + ")", con);

not all code paths return a value c# - private string and for loop

Hi before you mark this as a duplicate I have looked and tried others and had no luck. I keep getting the error for the string getBrand saying that:
not all code paths return a value.
private string getBrand(string id)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select brand from tbl_products where productId = '" + id + "'";
cmd.ExecuteNonQuery();
con.Close();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
getBrand = dt.Rows[0][0].ToString();
}
Below is where I get the string 'id' that pass to the getBrand String wish the run the query from.
for (int i = 0; i < salesGridView.Rows.Count; i++)
{
table2.AddCell(new Phrase(salesGridView[1, i].Value.ToString(), normFont));
string id = salesGridView[0, i].Value.ToString();
table2.AddCell(new Phrase(getBrand(id), normFont));
}
You've stored the dt.Rows[0][0].ToString(); into the method's name. You need to return the following line from your method:
return dt.Rows[0][0].ToString();
Or store it in a different variable's name and then return that variable. Like this:
var temp = dt.Rows[0][0].ToString();
return temp;
You should do it this way:
private string getBrand(string id)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select brand from tbl_products where productId = '" + id + "'";
cmd.ExecuteNonQuery();
con.Close();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
return dt.Rows[0][0].ToString();
}

How to get ID against selected value of Dropdownlist C#

How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.

Dropdown list from db, how to combine columns for DataTextField?

I have a dropdown list that gets populated from a datatabase. I have it working when wanting to display only the firstname in the DataTextField of the dropdown. But if i want to display 2 fields, firstname and lastname, then it throws an error. Why is this not working or how can i get it to work?
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_customers", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "Customers");
CustomerList.DataSource = ds.Tables[0];
CustomerList.DataTextField = "FirstName" + " " + "LastName";
CustomerList.DataValueField = "CID";
CustomerList.DataBind();
You have to select the "virtual" column from the database:
string sql = #"SELECT FirstName + ' ' + LastName AS FullName,
CID, FirstName, LastName
FROM tbl_customers
ORDER BY FullName ASC;"
SqlCommand cmd = new SqlCommand(sql, con);
// ...
CustomerList.DataSource = ds.Tables[0];
CustomerList.DataTextField = "FullName";
CustomerList.DataValueField = "CID";
CustomerList.DataBind();
You're going to want to define a custom column:
SqlCommand cmd = new SqlCommand("SELECT CID, FirstName + ' ' + LastName AS [FormattedName] FROM tbl_customers", con);
Then you can bind directly to that column:
CustomerList.DataTextFIeld = "FormattedName";
you can use database replicate method while joining the columns for the equal spacing..
string sql = #"SELECT FirstName + replicate(' ', 20 - len(FirstName)) + LastName AS FullName,
CID, FirstName, LastName
FROM tbl_customers
ORDER BY FullName ASC;"
SqlCommand cmd = new SqlCommand(sql, con);
CustomerList.DataSource = ds.Tables[0];
CustomerList.DataTextField = "FullName";
CustomerList.DataValueField = "CID";
CustomerList.DataBind();

Categories

Resources