ComboBox conected with data - database

I making a project in Visual Studio and I need to connect a Combobox to a database.
I have one set of data:
Audi - model 1
Audi - model 2
BMW - M1
If I select Audi in Combobox1 then in Combobox2 will only show model 1 and model 2.

I believe you are using c# with that you can filter out results for second dropdown based on first dropdown like this:
private void Combobox1_SelectionChangeCommitted(object sender, EventArgs e)
{
Combobox2.DataSource = null;
if (Combobox1.SelectedValue.ToString() != "0")
{
string sql = string.Format("SELECT CarModel FROM Table WHERE Car = {0}", Combobox1.SelectedValue);
Combobox2.DataSource = this.GetData(sql);
Combobox2.DisplayMember = "CarModel";
Combobox2.ValueMember = "ModelId"; //if there is an id for each model
Combobox2.Enabled = true;
}
}
Get Data Function:
private DataTable GetData(string sql)
{
string constr = #"Data Source=.\SQL2014;Initial Catalog=Cascading_ddl;Integrated Security=true"; //modify as per your project
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DataRow row = dt.NewRow();
row[0] = 0;
row[1] = "Please select";
dt.Rows.InsertAt(row, 0);
return dt;
}
}
}
PS: I have mentioned Combobox1, Combobox2 just to give the context, you should consider proper naming convention.

Related

I need to bound from query row to a label.text

Please look at code below and help me with your experience. I need to pull out company name from query and bound it to the lblCustName.text I tried different method but still I am getting errors. Please help to fix this problem.
public partial class frmMTO : Form
{
static string constring = ConfigurationManager.ConnectionStrings["cfTrack.Properties.Settings.Setting"].ConnectionString;
DataTable mtotbl = new DataTable("tbl");
public frmMTO()
{
InitializeComponent();
}
private void frmMTO_Load(object sender, EventArgs e)
{
btnStart.Enabled = false;
lblCustName.Text = "";
// Binding data to Customers List
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT Quote_No, Company FROM tblRFQ_logs ORDER BY Quote_No DESC", con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
cmRFQ.ValueMember = "id";
cmRFQ.DisplayMember = "Quote_No";
cmRFQ.DataSource = dt;
SqlDataAdapter materiaDA = new SqlDataAdapter("SELECT Grade FROM tblMaterialGrades", con);
DataTable materialDT = new System.Data.DataTable();
materiaDA.Fill(materialDT);
cmMaterial.ValueMember = "Grade_id";
cmMaterial.DisplayMember = "Grade";
cmMaterial.DataSource = materialDT;
// Closing Connection
con.Close();
mtotbl.Columns.Add("ID", typeof(int));
mtotbl.Columns.Add("Material", typeof(string));
mtotbl.Columns.Add("Item Mark", typeof(string));
mtotbl.Columns.Add("Short Code", typeof(string));
mtotbl.Columns.Add("Description", typeof(string));
mtotbl.Columns.Add("Unit", typeof(string));
mtotbl.Columns.Add("QTY.", typeof(string));
mtotbl.Rows.Add(1, "SA-106 B", "N1", "PIP4STD106","4in STD SA-106B, SMLS", "in.", "6");
dataGridView1.DataSource = mtotbl;
}
private void cmRFQ_SelectedValueChanged(object sender, EventArgs e)
{
// here I need to change the label text
lblCustName.Text = "Company" <------ this data comes from query
}
Thanks for your reply
Assuming that you bind the selected index change to this function.
cmRFQ.SelectedIndexChanged += new System.EventHandler(list_SelectedIndexChanged);
I think what you're looking for is this:
protected void list_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;
string value = (string)list.SelectedValue;
lblCustName.Text = value
}

How to generate linkage checkbox (C #)?

initial we will see two checkbox
No.1: Fruit
No.2: Animals
if select checkbox1 then display
□ Bananas
□ Apple
if select checkbox2 then display
□ Dog
□ Cat
□ Monkeys
I do not know how to write it with asp.net(c#), (they begin with SQL binding lists), thank you very much !!!
the initial two checkbox is use
Front End:
<asp:CheckBoxList ID="chkFruit_animal" runat="server"
onload="CheckBoxFruit_animal_Load" >
</asp:CheckBoxList>
Code Behined:
protected void CheckBoxFruit_animal_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sqlstr;
sqlstr = "SELECT DISTINCT * From fa";
MySqlDataAdapter myAdapter = new MySqlDataAdapter();
MySqlConnection dbconn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
DataSet ds = new DataSet();
myAdapter.SelectCommand = new MySqlCommand(sqlstr, dbconn);
myAdapter.Fill(ds, "fa");
chkFruit_animal.DataSource = ds.Tables["fa"];
chkFruit_animal.DataTextField = "faName";
chkFruit_animal.DataValueField = "faID";
chkFruit_animal.DataBind();
}
}
Database:
[fa]
faID|faname
1 |Fruit
2 |Animals
[teamName]
faID|Tname
1 |Bananas
1 |Apple
2 |Dog
2 |Cat
2 |Monkeys
Update code
Front End:
<div>
<div>
<asp:CheckBoxList ID="chkFruit_Animal" runat="server" OnCheckedChanged="chkFruit_Animal_CheckedChanged" ></asp:CheckBoxList>
</div>
<asp:CheckBoxList ID="chkBind" runat="server"></asp:CheckBoxList>
</div>
Code Behined
protected void Page_Load(object sender, EventArgs e)
{
//Console.WriteLine(json);
if (!IsPostBack)
{
//get the data from database
DataTable dtFruitAnimal = new DataTable("Name");
dtFruitAnimal.Columns.Add("faID");
dtFruitAnimal.Columns.Add("faname");
dtFruitAnimal.Rows.Add("1","Fruit");
dtFruitAnimal.Rows.Add("2","Animals");
chkFruit_Animal.DataSource = dtFruitAnimal;
chkFruit_Animal.DataTextField = "faID";
chkFruit_Animal.DataValueField = "faname";
chkFruit_Animal.DataBind();
}
}
protected void chkFruit_Animal_CheckedChanged(object sender, EventArgs e)
{
string value = chkFruit_Animal.SelectedValue;
DataTable dtResult = GetData(value);
chkBind.DataSource = dtResult;
chkBind.DataTextField = "faID";
chkBind.DataValueField = "Tname";
chkBind.DataBind();
}
public DataTable GetData(string strValue)
{
DataTable dt = new DataTable("DtResult");
string sqlQuery = "SELECT DISTINCT * From teamName where faId=#value";
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con))
{
da.SelectCommand.CommandType = CommandType.Text;
da.SelectCommand.Parameters.AddWithValue("#value", strValue);
da.Fill(dt);
}
}
return dt;
}

fill textbox on second combobox selection changed in cascading combobox in windows form using c#

I have 2 cascading combo-box in windows form application. I have textbox for price and unit. when I select first combobox, second combobox gets populated. I want textbox for price and unit to be filled only on second combobox selection.
My problem is when the form is loaded both textboxes are filled with values from table and not on combobox selection changed.
my code is:
private void Purchase_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'supplierDataSet.Supplier' table. You can move, or remove it, as needed.
this.supplierTableAdapter.Fill(this.supplierDataSet.Supplier);
fillName();
comboBoxName.SelectedIndex = -1;
}
private void fillName()
{
string str = "Select distinct Item_Name from Item";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Name";
}
}
}
}
private void fillMake()
{
string str = "Select Item_Make from Item Where Item_Name=#Item_Name";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
cmd.Parameters.AddWithValue("#Item_Name", comboBoxName.Text);
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxMake.DataSource = dtItem;
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.DisplayMember = "Item_Make";
}
}
}
}
private void comboBoxName_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text))
{
comboBoxMake.Enabled = true;
fillMake();
comboBoxMake.SelectedIndex = -1;
}
}
private void comboBoxMake_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxMake.Text))
{
textBoxPrice.Enabled = true;
textBoxUoM.Enabled = true;
}
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Item Where Item_Make='" + comboBoxMake.Text + "' AND Item_Name='" + comboBoxName.Text + "'", con);
SqlDataReader reader;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
reader = cmd.ExecuteReader();
while (reader.Read())
{
textBoxPrice.Text = Convert.ToString(reader["Price"]);
textBoxUoM.Text = Convert.ToString(reader["Unit"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
I am stuck here. please help.
Try changing SelectedIndex = -1 to SelectedItem = -1 in Purchase_Load and ComboBox1_SelectedIndexChanged.

ComboBox Shows System.Data.DataRow (MVC)

My Combobox does not show me the values in my SQL-Attribute "TimeBlock", instead it shows System.Data.DataRow 5 Times. What is wrong with my code?
Code:
//DAL:
public class DAL{
string ConnectionString = "server=ICSSQL13\\Grupp28,1528; Trusted_Connection=yes; database=Yoloswag";
public DataTable StoreSqlDataInComboBoxTP()
{
SqlConnection Conn = new SqlConnection(ConnectionString);
Conn.Open();
string StoreSqlDataInComboBoxTP = "SELECT TimeBlock FROM TimePeriod GROUP BY TimeBlock";
SqlCommand Cmd = new SqlCommand(StoreSqlDataInComboBoxTP, Conn);
SqlDataAdapter Adapter = new SqlDataAdapter(Cmd);
DataSet DSet = new DataSet();
Adapter.Fill(DSet);
Adapter.Dispose();
Cmd.Dispose();
Conn.Close();
Conn.Close();
return DSet.Tables[0];
}
}
//Controller:
public class Controller
{
DAL Dal = new DAL();
public DataTable storesqldataincomboboxtp()
{
return Dal.StoreSqlDataInComboBoxTP();
}
}
//View:
public partial class Booking : Form
{
Controller controller = new Controller();
DataTable DTable = new DataTable();
DataSet DSet = new DataSet();
//Ignore string UserName
public Booking(string UserName){
DTable = controller.storesqldataincomboboxtp();
if (DTable.Rows.Count > 0)
{
for (int i = 0; i < DTable.Rows.Count; i++)
{
CBTime.Items.Add(DTable.Rows[i].ToString());
}
}
}
}
Instead of the 5 System.Data.DataRow I want to show what is stored in "TimeBlock".
"SELECT TimeBlock From TimePeriod GROUP BY TimeBlock" shows:
"08-00 - 10:00"
"10:00 - 12:00"
"12:00 - 14:00"
"14:00 - 16:00"
"16:00 - 18:00"
How can i solve this?
Thanks
You are not getting to the Field level when you are calling the Add() on CBTime. Something like this within your conditional checking that your table has rows would work:
foreach (DataRow dRow in DTable.Rows)
{
CBTime.Items.Add(dRow["TimeBlock"]);
}

winform .net best way if you want to display images in a datagridview

net webdeveloper and usually don't make any win32 apps. but now i have to. i have a list with about 2000 entries.
each entry should be displayed as, a label with textbox another label and picture. i have made this with a flowlayoutpanel and i did a foreach on the entries to make a panel for each entry with the label, textbox, label and a picturebox.
now i have rendering issues when it comes above 1000 entries.
so i have read that i should use a listview or datagridview.
now i have a datagridview like this:
DataGridView dgv = new DataGridView();
dgv.AutoSize = true;
dgv.ScrollBars = ScrollBars.Vertical;
System.Data.DataTable dt = new System.Data.DataTable();
DataColumn dc1 = new DataColumn("Code", typeof(string));
dc1.ReadOnly = true;
dt.Columns.Add(dc1);
dt.Columns.Add(new DataColumn("Quantity", typeof(int)));
DataColumn dc3 = new DataColumn("Price", typeof(string));
dc3.ReadOnly = true;
dt.Columns.Add(dc3);
dt.Columns.Add(new DataColumn("Image", typeof(Bitmap)));
foreach (Product pd in products)
{
DataRow dr = dt.NewRow();
dr["Code"] = pd.ProductCode;
dr["Quantity"] = pd.ProductQuantity;
dr["Price"] = "€ " + String.Format("{0:0,00}", pd.ProductResalePrice.ToString());
dr["Image"] = BitmapFromWeb(pd.ProductImage);
dt.Rows.Add(dr);
}
dt.AcceptChanges();
dgv.RowTemplate.Height = 50;
dgv.DataSource = dt;
but the thing is that a bitmap on a datagridview is really slow! the picturebox option and panels which i had before where much faster. how do i resolve this?
the second question is: which event do i need when i want to track the changes made in the 2nd column?
ow one thing: the images are online available so the 'pd.ProductImage' is an url
private static Bitmap BitmapFromWeb(string URL)
{
try
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(myResponse.GetResponseStream());
myResponse.Close();
return bmp;
}
catch (Exception ex)
{
return null; // if for some reason we couldn't get to image, we return null
}
}
Do the image load asyncrhonously then force a refresh of the cell. You can put your foreach code into a call to the ThreadPool, something like...
ThreadPool.QueueUserWorkItem(delegate
{
foreach (DataRow row in dt)
{
row["Image"] = BitmapFromWeb(Products[row["Code"]].ProductImage);
//maybe a call to invalidate here, remember to do Control.Invoke(...)
}
}
Edit: here is a sample code that I tested inside the Form constructor...
DataTable t= new DataTable();
t.Columns.Add("id");
t.Columns.Add("uri");
t.Columns.Add(new DataColumn("Img",typeof(Bitmap)));
Bitmap b = new Bitmap(50, 15);
using (Graphics g = Graphics.FromImage(b))
{
g.DrawString("Loading...", this.Font, new SolidBrush(Color.Black), 0f,0f);
}
t.Rows.Add(new object[] { "1", "http://farm1.static.flickr.com/88/377522544_c4774f15cc_s.jpg", b });
t.Rows.Add(new object[] { "2", "http://farm1.static.flickr.com/175/377522405_2c505def99_s.jpg", b });
t.Rows.Add(new object[] { "3", "http://farm1.static.flickr.com/185/377524902_72f82e2db9_s.jpg", b });
t.Rows.Add(new object[] { "4", "http://farm1.static.flickr.com/136/377524944_d011abf786_s.jpg", b });
t.Rows.Add(new object[] { "5", "http://farm1.static.flickr.com/137/377528675_d3b9d541fb_s.jpg", b });
dataGridView1.DataSource = t;
ThreadPool.QueueUserWorkItem(delegate
{
foreach (DataRow row in t.Rows)
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(row["uri"].ToString());
myRequest.Method = "GET";
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(myResponse.GetResponseStream());
myResponse.Close();
row["Img"] = bmp;
}
});
dataGridView1.CellEndEdit += dataGridView1_CellEndEdit;
.... and in the cell end edit code:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string value = dataGridView1.Rows[e.RowIndex].Cells["uri"].Value.ToString();
ThreadPool.QueueUserWorkItem(delegate
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(value);
myRequest.Method = "GET";
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(myResponse.GetResponseStream());
myResponse.Close();
dataGridView1.Rows[e.RowIndex].Cells["Img"].Value=bmp;
});
}
// table is DataTable object declared as member in my form class
table = new DataTable();
table.Columns.Add(new DataColumn("Column1", typeof(string)));
table.Columns.Add(new DataColumn("Column2", typeof(string)));
table.Columns.Add(new DataColumn("Column3", typeof(System.Drawing.Bitmap)));
dataGridView1.DataSource = table;

Resources