这里发生了什么?
不是很理解控件运行的顺序和次数。请先看程序。
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 MIS_Information
{
public partial class frmHelpdeskModify : Form
{
int helpdeskid;
DataSet ds=new DataSet();
SqlConnection cn = new SqlConnection(Properties.Settings.Default.HY_MISConnectionString);
public frmHelpdeskModify(int helpdesk)
{
InitializeComponent();
helpdeskid = helpdesk;
}
private void frmHelpdeskModify_Load(object sender, EventArgs e)
{
getHelpdesk();
getcompany();
}
private void getHelpdesk()
{
if (helpdeskid != 0)
{
string sql = "Select HelpdeskID,HelpdeskUserName,Department,QuestionTitle,WhoAnswer,QuestionClassID,AnswerDetail,BeginTime,EndTime,Endsign,UserOrSystem,CompanyID From HelpdeskTable Where HelpdeskID=" + helpdeskid;
SqlDataAdapter da = new SqlDataAdapter(sql, cn);
cn.Open();
da.Fill(ds, "HelpdeskTable");
//MessageBox.Show(ds.Tables["HelpdeskTable"].Rows[0]["CompanyID"].ToString());
cn.Close();
}
}
private void getcompany()
{
string sql = "Select CompanyID,CompanyName From CompanyTable";
SqlDataAdapter da = new SqlDataAdapter(sql, cn);
cn.Open();
da.Fill(ds, "CompanyTable");
cn.Close();
CompanyTable.DataSource = ds.Tables["CompanyTable"];
CompanyTable.DisplayMember = "CompanyName";
CompanyTable.ValueMember = "CompanyID";
if (helpdeskid != 0) CompanyTable.SelectedValue = int.Parse(ds.Tables["HelpdeskTable"].Rows[0][11].ToString());
MessageBox.Show("End getCompany()");
}
private void CompanyTable_SelectedIndexChanged(object sender, EventArgs e)
{
if (CompanyTable.SelectedIndex >=-1)
{
// if (ds.Tables["DepartmentTable"] != null) ds.Tables["DepartmentTable"].Clear();
DataRowView adv = (DataRowView)CompanyTable.SelectedItem;
int CompanyID = int.Parse(adv.Row["CompanyID"].ToString());
string sql = "Select DepartmentID,DepartmentName From DepartmentTable Where CompanyID=" + CompanyID;
SqlDataAdapter da = new SqlDataAdapter(sql, cn);
cn.Open();
da.Fill(ds, "DepartmentTable");
cn.Close();
DepartmentTable.DataSource = ds.Tables["DepartmentTable"];
DepartmentTable.DisplayMember = "DepartmentName";
DepartmentTable.ValueMember = "DepartmentID";
if (helpdeskid != 0) DepartmentTable.SelectedValue = int.Parse(ds.Tables["HelpdeskTable"].Rows[0][2].ToString());
}
}
}
}
疑问一:
程序中通过断点发现,运后selectedindexchanged事件发生了3次,不是很能理解为什么会有三次的运行,想来想去能想到就是2次,第1次是在填充数据时,第2次是在改变数据时,第3次是什么呢?再想了想会不会是在初始化的时候也运行了呢?但有考虑到初始化时SelectedIndex应当是=-1的,应当不会运行呀。我在每次运行后都观察了SelectedIndex的值,分别是:0,null,1。
这个第1次的0是填充数据时的首个值,但是第2次的null是怎么产生的呢?第3次就是程序helpdeskid>0所产生的。
有没有人可以指点下第2次的SelectedIndex的null值是怎么来的呢?
周五,下班时间了,把问题稍后先放松会,晚点上微软去看看。