将新行添加到DataTable

时间:2012-10-13 00:56:11

标签: c# winforms gridview datatable devexpress

我的表单中有一个GeidView,我有一个按钮,通过向Datatable添加一行将新记录添加到GridView,然后将此DataTable作为GridContol的数据源。

问题是当我添加一个新的记录显示在GridView中但是当我添加另一个rocord时它没有显示在GridView中,GridView总是包含我添加到DataTable的第一行!

那么请你能帮我解决这个问题吗?

这是源代码:

private DataTable recompensesTable;

private void AjoutLivre_Load(object sender, EventArgs e)
        {
          recompensesTable = MakeRecomponsesTable();
          recompenseGridControl.DataSource = recompensesTable;
        }
private DataTable MakeRecomponsesTable()
        {
            DataTable recmpensesTable = new DataTable("Recompenses");

            var anneeColumn = new DataColumn();
            anneeColumn.DataType = Type.GetType("System.Int32");
            anneeColumn.ColumnName = "Année";
            recmpensesTable.Columns.Add(anneeColumn);

            var prixLiteraireColumn = new DataColumn();
            prixLiteraireColumn.DataType = Type.GetType("System.String");
            prixLiteraireColumn.ColumnName = "Prix Litéraire";
            recmpensesTable.Columns.Add(prixLiteraireColumn);

            return recmpensesTable;
        }

private void nouveauRecompense_Click(object sender, EventArgs e)
        {
            DataRow row = recompensesTable.NewRow();

            row[0] = ajoutRecompense.KeyWordAnnee;
            row[1] = ajoutRecompense.KeyWordPrixLiteraire;
            recompensesTable.Rows.Add(row);

            recompenseGridControl.DataSource = recompensesTable;
        }

3 个答案:

答案 0 :(得分:2)

在你的Page_Load中,您有recompensesTable = MakeRecomponsesTable();。这会覆盖更改并重新创建数据表值

在页面回发中,变量将恢复为其默认值,并且需要重新创建它们。您可以使用Session来维护您的值

private void AjoutLivre_Load(object sender, EventArgs e)
{
   if(!Page.IsPostBack)
   {
     DataTable recompensesTable = MakeRecomponsesTable();
     Session["recompensesTable"] = recompensesTable; //Save it to session the first time
     recompenseGridControl.DataSource = recompensesTable;
   }
}

并检索会话保留值

private void nouveauRecompense_Click(object sender, EventArgs e)
{
    DataTable recompensesTable = (DataTable) Session["recompensesTable"]; //retrieve it from session
    DataRow row =  recompensesTable.NewRow();

    row[0] = ajoutRecompense.KeyWordAnnee;
    row[1] = ajoutRecompense.KeyWordPrixLiteraire;
    recompensesTable.Rows.Add(row);

    Session["recompensesTable"] = recompensesTable; //save it back to session

    recompenseGridControl.DataSource = recompensesTable;
}

答案 1 :(得分:0)

改变你的

private void AjoutLivre_Load(object sender, EventArgs e)
    {
      recompensesTable = MakeRecomponsesTable();
      recompenseGridControl.DataSource = recompensesTable;
    }

private void AjoutLivre_Load(object sender, EventArgs e)
    {
      if(!IsPostback)
         recompensesTable = MakeRecomponsesTable();
      recompenseGridControl.DataSource = recompensesTable;
    }

您还必须将数据表保存到会话

答案 2 :(得分:-1)

recmpensesTable始终是一个新的DateTable,您应将其保存到会话中以供下次使用。