Thank you guys in advance. I'am new user in c# Windows Forms.
I have a table with id's and name
ID | Name --------------- 1 | Lion 2 | Tiger 3 | Crocodile
If I want to display from a table to combobox I did like this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Insert_update_delete_nr2
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(@"CONNECTION_STRING");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
con.Open();
string query = "select * from info";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
while (dr.Read())//while true
{
comboBox1.Items.Add(dr[0].ToString());//loading values into combo
}
cmd.CommandText = "insert into info3 (name, name_id) values ('"+textBox1.Text+"', '" + comboBox1.Items.Add(dr[0].ToString()) + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
con.Close();
}
private void loadlist()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
con.Open();
cmd.CommandText = "select * from info3";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1]).ToString();
listBox3.Items.Add(dr[3].ToString());
}
}
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// con.Open();
FillDropDownList(string SQL, ComboBox comboBox1);// This giving me error.
// How should I call this FillDropDownlist function? The parameters which are they?
cmd.Connection = con;
listBox3.Visible = false;
loadlist();
}
}
}
And it's trying inserting what is showing in combobox which it's name, not id's.
in PHP it would be like the following:
$sql = " SELECT * FROM info ";
$res = mysql_query($sql);
while ($row = mysql_fetch_array($res)) {
print '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
That would insert id's and showing names. But How should I do in c#? Thank you again for your time!
Instead of adding the name string to the combobox, you could add a custom type, instead:
class Animal
{
public int ID { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
Create an object of that type for each entry (var animal = new Animal { ID = (int)dr[0], Name = (string)dr[1] };
), add the object to the combobox. Then when you go to retrieve it, simply cast the item to an Animal type and grab the ID.
var animal = (Animal)comboBox1.SelectedItem;
If I understand your question correctly, this should do what you are seeking:
Load your combo box with something like THIS (I can't test this right now, so I may have made some typo's or minor syntax errors):
**UPDATED: Ok. That is the LAST time I try to answer a question "on the go" when I'm in a rush. My original code was rife with issues and stupid typos. My sincere apologies! The following code includes a very basic version of everything you are trying to do. You may need to adapt it to suit your needs.
Some suggestions:
A. Place your connection and command in the using blocks, as shown.
B. Instead of hard-coding your connection string in your code, use the Properties.Settings designer in the Solutions Explorer (off to the left) and create a central reference for your connection string. Then reference it in code like shown.
The following performs the basic functionality you are trying to achieve, and runs on my machine:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(button1_Click);
this.FillDropDownList();
}
void button1_Click(object sender, EventArgs e)
{
this.SaveComboBoxContent();
}
public void FillDropDownList()
{
string SQL = "SELECT id, name FROM info ORDER BY name";
DataTable dt = new DataTable();
// Set the connection string in the Solutions Explorer/Properties/Settings object (double-click)
using (var cn = new SqlConnection(Properties.Settings.Default.MyConnectionString))
{
using(var cmd = new SqlCommand(SQL, cn))
{
cn.Open();
try
{
dt.Load(cmd.ExecuteReader());
}
catch (SqlException e)
{
// Do some logging or something.
MessageBox.Show("There was an error accessing your data. DETAIL: " + e.ToString());
}
}
}
// UPDATED - The .ValueMember and .DisplayMember properties
// refer to the string name of the field (oops!):
comboBox1.DataSource = dt;
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "name";
}
public void SaveComboBoxContent()
{
string SQL = "INSERT INTO info2 (name_id) VALUES (@name_id)";
using (var cn = new SqlConnection(Properties.Settings.Default.MyConnectionString))
{
using(var cmd = new SqlCommand(SQL, cn))
{
cmd.Parameters.AddWithValue("@name_id", comboBox1.SelectedValue);
cn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
// Do some logging or something.
MessageBox.Show("There was an error accessing your data. DETAIL: " + e.ToString());
}
}
}
}
}
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With