有没有办法在C#中重用数据集?我想使用断开连接的体系结构
我有一个数据集,它已经保存了DB中的一个表,我必须在下拉列表事件中使用相同的数据集。 但是,我理解了为什么数据集在到达程序中的捕获之前是空的。除了在regionDropDownList\u SelectedIndexChanged事件中再次建立新连接外,还有其他重写方法吗?下面是我的代码。非常感谢:) 现在如果发生selectedindexchanged事件有没有办法在C#中重用数据集?我想使用断开连接的体系结构,c#,C#,我有一个数据集,它已经保存了DB中的一个表,我必须在下拉列表事件中使用相同的数据集。 但是,我理解了为什么数据集在到达程序中的捕获之前是空的。除了在regionDropDownList\u SelectedIndexChanged事件中再次建立新连接外,还有其他重写方法吗?下面是我的代码。非常感谢:) 现在如果发生selectedindexchanged事件 public void regionDropDownList_SelectedIndexChanged(object sender, Ev
public void regionDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
regionDropDown();
foreach (DataRow row in mySet.Tables["Regions"].Rows)
{
if (regionDropDownList.SelectedValue == row["RegionID"].ToString())
{
regionDescriptionLabel.Text = row["RegionDescription"].ToString();
}
}
}
catch (Exception ex) { regionDescriptionLabel.Text = "Caught!!" + ex; }
}
为什么在这里再次调用regionDropDown()
谢谢你的快速回复。我同意“数据集mySet”,我正在测试,但忘了删除它。我已经优化了for循环中的列表,谢谢。另外,只想添加,我的表(Region)有RegionID,RegionDescription作为列。我的情况是在页面加载期间加载带有RegionID的下拉列表,然后当我从下拉列表中选择ID时,它必须从Region表中显示关联的RegionDescription。
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
regionDropDown();
}
}
DataSet mySet; // ?
public void regionDropDown() {
// Define ADO.NET objects.
string connectionString = WebConfigurationManager.ConnectionStrings["northwindConString"].ConnectionString;
SqlConnection myConn = new SqlConnection(connectionString);
myConn.Open();
SqlCommand cmd = new SqlCommand("Select * FROM Region", myConn);
SqlDataAdapter daRegion = new SqlDataAdapter(cmd);
DataSet dsRegion = new DataSet();
daRegion.Fill(dsRegion, "Region");
mySet = dsRegion;
// If you want,custom logic then you might use this code,
// else just provide datatextfield and datavalue field before binding..
foreach (DataRow row in dsRegion.Tables["Region"].Rows)
{
ListItem ls = new ListItem();
ls.Text = row["RegionID"].ToString();
ls.Value = row["RegionID"].ToString();
regionDropDownList.Items.Add(ls);
}
myConn.Close();
}
public void regionDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
regionDropDown();
foreach (DataRow row in mySet.Tables["Regions"].Rows)
{
if (regionDropDownList.SelectedValue == row["RegionID"].ToString())
{
regionDescriptionLabel.Text = row["RegionDescription"].ToString();
}
}
}
catch (Exception ex) { regionDescriptionLabel.Text = "Caught!!" + ex; }
}
public void regionDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
regionDescriptionLabel.Text = regionDropDownList.SelectedItem.Text; // If value needed then regionDropDownList.SelectedValue
}