フォームに 2 つのドロップダウン リストを追加し、次のように名前を付けますcmbStates
。cmbCities
から州名を選択すると、州名に基づいて都市を生成します(cmbStates cmbStates(dropwdownlist)
)cmbCities(dropdownlist)
データベースからデータを取得することにより
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=pbs-server;database=p2p;user id=shekar;password=sekhar@1346");
SqlCommand cmd = new SqlCommand("select states from Country", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "Country");
cmbStates.DataSource = ds.Tables[0];
cmbStates.SelectedValue = 0;
con.Close();
}
private void cmbStates_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=xxxx;database=xxxx;user id=xxxxr;password=xxxxxx");
SqlCommand cmd = new SqlCommand("select cities from States where cityname = 'cmbStates.SelectedItem.ToString()'", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "States");
cmbCities.DataSource = ds.Tables[0];
cmbCities.SelectedValue = 0;
con.Close();
}
また
アイテムを手動で追加する
namespace DropDownlist
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmbStates.Items.Add("Andhra Pradesh");
cmbStates.Items.Add("Tamilnadu");
cmbStates.Items.Add("Karnataka");
cmbStates.SelectedValue = 0;
}
private void cmbStates_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbStates.SelectedItem.ToString() == "Andhra Pradesh")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Hyderabad");
cmbCities.Items.Add("Guntur");
cmbCities.Items.Add("Vijayawada");
cmbCities.SelectedValue = 0;
}
else if (cmbStates.SelectedItem.ToString() == "Tamilnadu")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Chennai");
cmbCities.Items.Add("Coimbatore");
cmbCities.Items.Add("ooty");
cmbCities.SelectedValue = 0;
}
else if (cmbStates.SelectedItem.ToString() == "Karnataka")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Bangalore");
cmbCities.Items.Add("Mangalore");
cmbCities.SelectedValue = 0;
}
else
{
MessageBox.Show("Please Select any value");
}
}
}
}