Add rows in a gridview c#

蓝咒 提交于 2020-01-03 01:55:50

问题


Im new in asp.net. I want to know how to add a row in a gridview programatically. I was able to do it but it just displays the latest addition. Here is my code:

DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();

回答1:


Its because you are creating new table each time and binding it with the grid

Do code as below may resolve your issue ...

here i am taking existing datasource and binding it again by adding two more row...

DataTable dt = gridView.DataSource as DataTable;

if (dt != null)
{

  DataRow dr = dt.NewRow();
  dr["Question"] = txtQuestion.Text;
  dr["Answer"] = txtAnswer.Text;
  dt.Rows.Add(dr);
  dt.AcceptChanges();

  gvQnA.DataSource = dt;
  gvQnA.DataBind();
}



回答2:


@Pranay is correct.In addition You can also achive that by using DataTable as property.

  private DataTable Dt
    {
        set { ViewState.Add("Dt", value); }
        get { return (DataTable)ViewState["Dt"]; }
    }

...

DataRow dr = Dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
Dt.Rows.Add(dr);
Dt.AcceptChanges();

gvQnA.DataSource = Dt;
gvQnA.DataBind();



回答3:


You have added one row in your code thats why it is showing one row. If you have added multiple rows it would have shown proper result

DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);

**DataRow dr = dt.NewRow();
dr["Question"] = "2nd row";
dr["Answer"] = "2nd row";
dt.Rows.Add(dr);**

dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();

May be @Pranay is also right




回答4:


Hey Just check this. This might help u

DataTable dataTable = new DataTable();

int columnsCount = // Set the number of the table's columns here.

for (int columnIndex = 0; columnIndex < columnsCount; columnIndex++)
{
    DataColumn dataColumn = new DataColumn();
    // Assign dataColumn properties' values here ..
    dataTable.Columns.Add(dataColumn);
}

int rowsCount = // Set the number of the table's rows here.

for (int columnIndex = 0; columnIndex < columnsCount; columnIndex++)
{
    DataRow dataRow = new DataRow();
    dataRow["ColumnName"] = // Set the value here ..
    dataTable.Rows.Add(dataRow);        
}


来源:https://stackoverflow.com/questions/6213777/add-rows-in-a-gridview-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!