簡體   English   中英

如何使用C#在gridview中添加新行?

[英]how to add a new row in gridview using C#?

我想在修改記錄后從數據庫中檢索數據,然后在Gridview中顯示它。

我已經通過Edit columns創建了列名稱,這些名稱是Date,Location,Job Title,Details

這是我的asp.net代碼

<asp:GridView ID="GridViewRecord" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:BoundField HeaderText="Date" />
                    <asp:BoundField HeaderText="Location" />
                    <asp:BoundField HeaderText="Job Title" />
                    <asp:BoundField HeaderText="Experience" />
                    <asp:HyperLinkField HeaderText="Details" />
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>

然后,我嘗試直接添加一個樣本記錄。 但是我遇到了錯誤。 這是我在頁面加載時的C#代碼

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();

        DataRow dr = dt.NewRow();
        dr[0] = "12-12-12"; //Error message occured here
        dr[1] = "Jeddah";
        dr[2] = "Java";
        dr[3] = "2";
        dr[4] = "View Details";

        dt.Rows.Add(dr);
        GridViewRecord.DataSource = dt;
        GridViewRecord.DataBind();
    }
}

錯誤信息:

System.Data.dll中發生類型'System.IndexOutOfRangeException'的異常,但未在用戶代碼中處理
附加信息:找不到列0。

我是C#的新手,謝謝

您尚未向DataTable添加任何列,這就是為什么。

// Create a new DataTable object.
DataTable table = new DataTable();

// Declare a DataColumn
DataColumn column;

// Create the new DataColumn, set DataType, ColumnName and add then add to DataTable.    
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
table.Columns.Add(column);

// I think that the line-by-line explanation is better for the purpose of this answer
// you can of course do all of this in one row, assuming that you already have a datatable
table.Columns.Add("id", typeof(int));

但是,在您的示例中,您正在創建自己的DataTable ,為什么不使用數據庫中的那個呢? 那將已經有與您的選擇查詢匹配的列。

// create DataSet
DataSet ds = new DataSet();

// your operations for filing the DataSet with data from the database which you have not shared
// ...
// ...

// check to see whether we have a DataTable in the DataSet (if the query fails, ds.Tables.Count == 0)
if (ds.Tables.Count > 0) {
   DataRow row = ds.Tables[0].NewRow();
   // add data according to the schema
   // e.g.
   row["id"] = "blah";
   // add the rest of the columns

   // and lastly add the newly created row to the DataTable;
   ds.Tables[0].Rows.Add(row);
}

// now bind
GridViewRecord.DataSource = ds.Tables[0];
GridViewRecord.DataBind();

您還可以使用通用列表或字符串列表,這將使您的代碼變得簡單,而且性能明智的DataTable與list相比並不理想

例如:

List<string> lstRecord = new List<string>
{
    "12-12-12",
    "Jeddah",
    "Java",
    "2",
    "View Details"
};
GridViewRecord.DataSource = lstRecord;
GridViewRecord.DataBind();
  if (!this.IsPostBack)
            {   DataTable dt = new DataTable();
                dt.Columns.Add("0");
                dt.Columns.Add("1");
                dt.Columns.Add("2");
                dt.Columns.Add("3");
                dt.Columns.Add("4");

                DataRow dr = dt.NewRow();
                dr[0] = "12-12-12"; //Error message occured here
                dr[1] = "Jeddah";
                dr[2] = "Java";
                dr[3] = "2";
                dr[4] = "View Details";

                dt.Rows.Add(dr);
                GridViewRecord.DataSource = dt;
                GridViewRecord.DataBind();
            }

您需要添加到DataTable列以使其工作(0,1,2,3,4)響應表數組,就像您編寫dr [0] = Add(“ 0”);

或者您可以輕松地在想要插入日期的列上進行操作

dr["2"]= "Java";  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM