1

データベースに値を挿入するグリッドビューがありますが、常に最新の値が表示されます (ラベルを使用してテストしました)。データベース内のすべての値 (複数行) を入力して、グリッド ビューの各行の値をデータベース内の複数行に挿入するようにしたいと考えています。

ここに私のグリッドビューがあります:

ここに画像の説明を入力

すべての行の値をデータベースに保存する必要があります。これが私のコードです:

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(); 
    }
}
4

1 に答える 1

1

TextBox1 と TextBox2 は、Grid 全体で同じです。異なるグリッドから TextBox1 と TextBox2 を選択しても役に立ちません。同じ 2 つの TextBox から値を取得するだけです。

TextBoxes をリストに追加してから、テキストを取得してデータベースに挿入してみてください。

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();
}
于 2013-05-29T02:31:28.320 に答える