[英]C#, Delete first row from gridview element
這已經被問過很多次了,但是我似乎找不到直接的答案。
使用C#,我使用數據表填充gridview。 數據表的第一行包含表標題,因此我遍歷該行並填充gridview標題行。 但是現在我需要擺脫表中的第一行(標題行)。 我四處張望,所有消息來源都同意正確的語法是:
strSQL = "SELECT * FROM [Station ID Request$]";
OleDbDataAdapter adaBatch = new OleDbDataAdapter(strSQL, strConnExcel);
DataTable dtBatch = new DataTable();
adaBatch.Fill(dtBatch);
gv_stations.DataSource = dtBatch;
gv_stations.DataBind();
// Fill gridview headers with first row of data (spreadsheet headers)
int i = 0;
foreach (DataColumn col in dtBatch.Columns)
{
gv_stations.HeaderRow.Cells[i].Text = dtBatch.Rows[0][i].ToString();
i++;
}
// Remove the first line of the gridview (contains header info)
gv_stations.DeleteRow(0);
除了最后一行,一切正常,這給了我這個錯誤:
System.Web.HttpException (0x80004005): The GridView 'gv_stations' fired
event RowDeleting which wasn't handled. at
System.Web.UI.WebControls.GridView.OnRowDeleting(GridViewDeleteEventArgs e)
at System.Web.UI.WebControls.GridView.HandleDelete(GridViewRow row, Int32
rowIndex) at System.Web.UI.WebControls.GridView.DeleteRow(Int32 rowIndex)
我嘗試過的所有資源都說最后一行應該沒問題。 誰能說出為什么我會收到該錯誤?
編輯:這是我的gridview對象,根據要求。
<asp:GridView ID="gv_stations" runat="server"
AutoGenerateColumns="True"
CssClass="c_gvv c_gvv_stations_results"
style="white-space:nowrap;">
</asp:GridView>
您正在嘗試從GridView
刪除一行,而應該從DataTable
刪除它。 使用此行:
dtBatch.Rows[0].Delete();
代替這個:
gv_stations.DeleteRow(0);
您也可以簡單地循環:
for(int i = 0; i < dtBatch.Columns.Count; i++)
gv_stations.HeaderRow.Cells[i].Text = dtBatch.Rows[0][i].ToString();
完整的代碼:
...
//Fill gridview headers with first row of data (spreadsheet headers)
for(int i = 0; i < dtBatch.Columns.Count; i++)
gv_stations.HeaderRow.Cells[i].Text = dtBatch.Rows[0][i].ToString();
//Remove the first line of the gridview (contains header info)
dtBatch.Rows[0].Delete();
//now do the bindings
gv_stations.DataSource = dtBatch;
gv_stations.DataBind();
閱讀完您對其他答案的評論后,對於您所說的問題,我有些困惑。 是否只是將綁定綁定到gridview,那么數據表中的第一行(標題)就會同時顯示為gridview中的標題行和數據的第一行?
似乎很奇怪,如果您不希望先檢索標頭行,然后再經歷用foreach循環添加所有標頭的麻煩,然后再嘗試將其刪除。
如果您不想首先選擇標題行,則可以修改連接字符串(大概是strConnExcel?),使其包含“ HDR = No”,這將阻止其將第一行帶回第一行。
但是,如果要標題行,則使用“ HDR = Yes”,然后簡單地綁定到您的gridview。 它會知道標題行是什么。 盡管看起來像您嘗試添加標題行然后將其刪除!
您正在將GridView綁定到數據源:
gv_stations.DataSource = dtBatch; gv_stations.DataBind();
從數據源中將其刪除,然后進行數據綁定,或者從DataGrid中將其刪除,而無需重新綁定數據。
或者,如果您希望將其保留在其中,則可以使其不可見:
gv_stations.rows [0]。可見=假
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.