请教!Web开发中GridView没有正常显示数据的问题
本人刚开始学习用VC#.net开发Web项目,这些天用Gridview做数据库开发时遇到一个问题。用GridView连接数据库后,第一次加载数据时,GridView不能正常显示出来,第二次加载数据才能正常显示,而且显示的数据也是正确的。这个问题在想了两三天了,在网上也没找到答案。希望哪位大侠给些指点,不胜感激!!!
我的代码如下:
protected void btnHouse_Click(object sender, EventArgs e)
{
string strConnection = "Persist Security Info=false;Integrated Security=true;Initial Catalog=House;server=(local) ";
SqlConnection sqlConn = new SqlConnection(strConnection);
sqlConn.Open();
//“id”是从上一个页面通过Transer()方法传递的参数,string类型变量
string strSelect = "select UserID,UserName,Sex from [UserData] where UserID= ' " + id + " ' ";
SqlDataAdapter sqlDAdapter = new SqlDataAdapter(strSelect, sqlConn);
DataSet dSet = new DataSet();
sqlDAdapter.Fill(dSet, "tblUserData ");
sqlConn.Close();
GridView1.Visible = true;
GridView1.DataSource = dSet.Tables[ "tblUserData "];
GridView1.DataBind();
BoundField bdf1 = new BoundField();
bdf1.DataField = "UserID ";
bdf1.HeaderText = "User ID ";
GridView1.Columns.Add(bdf1);
BoundField bdf2 = new BoundField();
bdf2.DataField = "UserName ";
bdf2.HeaderText = "User Name ";
GridView1.Columns.Add(bdf2);
BoundField bdf3 = new BoundField();
bdf3.DataField = "Sex ";
bdf3.HeaderText = "Sex ";
GridView1.Columns.Add(bdf3);
}
------解决方案--------------------动态添加列得在【绑定语句】之前完成
》》》
BoundField bdf1 = new BoundField();
bdf1.DataField = "UserID ";
bdf1.HeaderText = "User ID ";
GridView1.Columns.Add(bdf1);
BoundField bdf2 = new BoundField();
bdf2.DataField = "UserName ";
bdf2.HeaderText = "User Name ";
GridView1.Columns.Add(bdf2);
BoundField bdf3 = new BoundField();
bdf3.DataField = "Sex ";
bdf3.HeaderText = "Sex ";
GridView1.Columns.Add(bdf3);
GridView1.DataSource = dSet.Tables[ "tblUserData "];
GridView1.DataBind();
------解决方案--------------------如果是Jinglecat写的那样的话,GridView1不是要多显示三列啊!
------解决方案--------------------刚刚测试过,你的代码不仅第一次不能显示数据,而且每次点击按钮后,都会重复自动增加列。
下面的代码能够解决第一次不能显示数据的问题。 但是自动增加列的问题,还需要你自己处理了
嘿嘿嘿嘿,嘿嘿嘿嘿,嘿嘿嘿嘿,嘿嘿嘿嘿,嘿嘿嘿嘿
GridView1.DataSource = dSet.Tables[ "tblUserData "];
BoundField bdf1 = new Bound