问题描述
publicpartialclass_Default:System.Web.UI.Page{protectedvoidPage_Load(objectsender,EventArgse){stringConStr=@"Server=(local)sqlexpress;DataBase=db_07;Uid=sa;Pwd=a963.";stringcmdtxt="SELECT*FROMtb_07";SqlConnectionCon=newSqlConnection(ConStr);SqlDataAdapterda=newSqlDataAdapter(cmdtxt,Con);DataSetds=newDataSet();da.Fill(ds);this.GridView1.DataSource=ds;this.GridView1.DataBind();if(ViewState["Count"]!=null){for(inti=0;i<Convert.ToInt16(ViewState["Count"]);i++){//AddTextBox();Response.Write("<script>allert('ViewState!=null当!当!当!当!');</script>");}}else{this.btnData.Enabled=false;Response.Write("<script>allert('ViewState==null哈哈!');</script>");}}//向页面中添加文本框publicvoidAddTextBox(){//行TableRowtr=newTableRow();//单元格1TableCelltc1=newTableCell();//TextBoxTextBoxtxt=newTextBox();txt.ID="tb"+Table1.Rows.Count;txt.Font.Size=FontUnit.Point(9);//单元格2TableCelltc2=newTableCell();//LabelLabellab=newLabel();lab.ID="lab"+Table1.Rows.Count;lab.Width=50;lab.Text="数据"+(Table1.Rows.Count+1);tc2.Controls.Add(lab);tc1.Controls.Add(txt);tr.Cells.Add(tc2);tr.Cells.Add(tc1);Table1.Rows.Add(tr);}protectedvoidButton1_Click(objectsender,EventArgse){Response.Write("<script>allert('添加输入框');</script>");//动态添加控件AddTextBox();ViewState["Count"]=Convert.ToInt16(ViewState["Count"])+1;this.btnData.Enabled=true;}protectedvoidbtnData_Click(objectsender,EventArgse){Response.Write("<script>allert('开始插入');</script>");stringConStr=@"Server=(local)sqlexpress;DataBase=db_07;Uid=sa;Pwd=a963.";SqlConnectionCon=newSqlConnection(ConStr);Con.Open();SqlCommandCom;stringcmdtxt=String.Empty;//将文本框中的内容循环插入到数据库中for(inti=0;i<Table1.Rows.Count;i++){cmdtxt="INSERTINTOtb_07(name)VALUES('"+((TextBox)Table1.Rows[i].FindControl("tb"+i)).Text+"')";Com=newSqlCommand(cmdtxt,Con);Com.ExecuteNonQuery();}Response.Write("<script>allert('数据插入成功!');location='Default.aspx'</script>");}}在上面,为什么在Page_Load里面,要再次执行AddTextBox();呢,如果不执行,发现添加不了数据。点击添加数据按钮后,不是直接读取输入框中的数据就行了,为什么还要再一次生成输入框?我是新手,自学来着,请指点一下
解决方案
解决方案二:
再page_load里面加一个判断if(!ispostback){stringConStr=@"Server=(local)sqlexpress;DataBase=db_07;Uid=sa;Pwd=a963.";stringcmdtxt="SELECT*FROMtb_07";SqlConnectionCon=newSqlConnection(ConStr);SqlDataAdapterda=newSqlDataAdapter(cmdtxt,Con);DataSetds=newDataSet();da.Fill(ds);this.GridView1.DataSource=ds;this.GridView1.DataBind();if(ViewState["Count"]!=null){for(inti=0;i<Convert.ToInt16(ViewState["Count"]);i++){//AddTextBox();Response.Write("<script>allert('ViewState!=null当!当!当!当!');</script>");}}else{this.btnData.Enabled=false;Response.Write("<script>allert('ViewState==null哈哈!');</script>");}}