001.
public
partial
class
Form1 : Form
002.
{
003.
public
Form1()
004.
{
005.
InitializeComponent();
006.
}
007.
008.
private
void
Form1_Load(
object
sender, EventArgs e)
009.
{
010.
011.
string
cmdText =
"select * from tblServiceType"
;
012.
013.
try
014.
{
015.
016.
ComboBoxDataBinding(comboServiceType, cmdText,
"ServiceTypeName"
,
"ServiceTypeID"
);
017.
}
018.
catch
(Exception ex)
019.
{
020.
MessageBox.Show(ex.Message);
021.
}
022.
}
023.
024.
025.
private
void
comboServiceType_SelectedIndexChanged(
object
sender, EventArgs e)
026.
{
027.
028.
string
serviceTypeID =
this
.comboServiceType.SelectedValue.ToString();
029.
030.
031.
string
cmdText =
"select * from tblServiceAreas where ServiceTypeID = @ServiceTypeID"
;
032.
033.
try
034.
{
035.
036.
ComboBoxDataBinding(
this
.comboServiceArea, cmdText,
"ServiceAreaName"
,
"ServiceAreaID"
, serviceTypeID);
037.
}
038.
catch
(Exception ex)
039.
{
040.
MessageBox.Show(ex.Message);
041.
}
042.
}
043.
044.
045.
046.
private
SqlConnection BuildConnection()
047.
{
048.
string
connectionString =
"server=(local)\\SQLEXPRESS;database=DBTest;Integrated Security=SSPI;"
;
049.
return
new
SqlConnection(connectionString);
050.
}
051.
052.
053.
054.
055.
056.
private
void
ComboBoxDataBinding(ComboBox comboBox,
string
cmdText,
string
displayMember,
string
valueMember)
057.
{
058.
059.
ComboBoxDataBinding(comboBox, cmdText, displayMember, valueMember,
null
);
060.
}
061.
062.
063.
064.
065.
066.
067.
private
void
ComboBoxDataBinding(ComboBox comboBox,
string
cmdText,
string
displayMember,
string
valueMember,
params
string
[] list)
068.
{
069.
try
070.
{
071.
DataTable dataTable =
null
;
072.
073.
074.
using
(SqlConnection sqlConnection = BuildConnection())
075.
076.
using
(SqlCommand sqlCommand =
new
SqlCommand(cmdText, sqlConnection))
077.
using
(SqlDataAdapter sqlDataAdapter =
new
SqlDataAdapter(sqlCommand))
078.
{
079.
DataSet dataSet =
new
DataSet();
080.
081.
sqlConnection.Open();
082.
083.
084.
if
(list !=
null
)
085.
{
086.
087.
string
[] parameters = cmdText.Split(
'@'
);
088.
089.
for
(
int
i = 0; i < list.Length; i++)
090.
{
091.
092.
093.
094.
sqlCommand.Parameters.Add(
new
SqlParameter(
"@"
+ parameters[i + 1].Trim(), list[i]));
095.
}
096.
}
097.
098.
sqlDataAdapter.Fill(dataSet);
099.
sqlConnection.Close();
100.
101.
if
(dataSet.Tables.Count > 0)
102.
{
103.
104.
dataTable = dataSet.Tables[0];
105.
}
106.
}
107.
108.
109.
if
(dataTable !=
null
)
110.
{
111.
comboBox.DisplayMember = displayMember;
112.
comboBox.ValueMember = valueMember;
113.
comboBox.DataSource = dataTable;
114.
}
115.
}
116.
catch
(Exception ex)
117.
{
118.
throw
ex;
119.
}
120.
}
121.
}