2013-05-29 102 views
1

我有一个gridview插入值到数据库,但它总是显示最新值(我使用标签测试)。我想让它在网格视图中输入每行的数据库(多行)值中的所有值,以便插入到数据库中的多行中。为循环值保存到数据库

这里是我的网格视图:

enter image description here

我需要每一行的值保存到数据库中。这里是我的代码:

protected void btnCreate_Click(object sender, EventArgs e) 
{ 
    if (int.TryParse(testLabel.Text, out number))//Click count 
    { 
     testLabel.Text = (++number).ToString(); 
    } 

    DataTable dt = (DataTable)ViewState["CurrentTable"]; 
    if (dt.Rows.Count > 0) 
    { 
     for (int i = 0; i < dt.Rows.Count; i++) 
     { 
      TextBox box1 = (TextBox)GridView1.Rows[i].Cells[1].FindControl("TextBox1"); 
      TextBox box2 = (TextBox)GridView1.Rows[i].Cells[2].FindControl("TextBox2"); 

      Model.question act = new Model.question(); // Entity Model CRUD 
      act.Answer = box2.Text; //Always show the last value. 
      act.QuestionContent = box1.Text; // Always show the last value. 
      act.TaskName = "Grammar"; 
      act.ActivityName = dropListActivity.SelectedItem.Text; 
      act.QuestionNo = testLabel.Text; 

      daoQuestion.Insert(act);  
     } 

     daoQuestion.Save(); 
    } 
} 
+0

什么是'ViewState [“CurrentTable”]',是GridView的源代码? –

+0

我将数据存储在viewstate中。 – user2376998

+0

我编辑了你的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –

回答

1

TextBox1和TextBox2在整个网格中都是一样的。通过从不同的网格中选择TextBox1和TextBox2不会有帮助,您只需从相同的两个文本框中获取值即可。

尝试将文本框添加到列表中,然后获取文本并插入到数据库中。

要将TextBox添加到列表中,您可以执行此操作。

List<TextBox> tbList = new List<TextBox>(); 
tbList.Add(new TextBox{ Name="textbox"+i++ }); 

随后,要抓住数值,就这样做。

for(int i = 0; i < tbList.Count; i++) 
{ 
    //To see the data you're inserting into database. 
    Response.Write(tb[i].Text); 
    Response.Write(tb[i+1].Text); 
    //Insert into database based on your code. 
    daoQuestion.Insert(new Model.question 
    { 
     Answer = tb[i].Text, 
     QuestionContent = tb[++i].Text, 
     TaskName = "Grammar", 
     ActivityName = dropListActivity.SelectedItem.Text, 
     QuestionNo = testLabel.Text 
    }); 
    daoQuestion.Save(); 
} 
+0

是的,但我如何保存每个值到数据库? – user2376998

+0

更新了答案,试试吧。 – Jieqin

+0

wad名称=文本框中的名称是指? – user2376998