开发者

Add rows in a gridview c#

Im new in asp.net. I want to know how to add a row in a gridview programatically. I w开发者_JAVA百科as 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();


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


@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();


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


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);        
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜