C#Datatable列名称更改问题

时间:2017-09-14 19:53:17

标签: c# asp.net data-binding columnname datacolumn

这是我在这里的第一篇文章,我是编程新手。现在,我正在尝试更改数据从sql数据库中获取的DataTable中的列名。在使用foreach循环更改列名后,似乎在我更改了数据表的列名后,程序在将其绑定到gridview后立即崩溃。 the error occur

知道导致错误的原因是什么?

C#代码背后:

//custom query generator
Session["query"] = db.generate_query(parameter1, parameter2, parameter3, parameter4);
//connecting sql
SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=ISMS;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand(Session["query"].ToString(),conn);
SqlDataAdapter sdal = new SqlDataAdapter(cmd1);


//when search is needed
dt_table = new DataTable();
sdal.Fill(dt_table);
// dataTable.Columns["ExistingColumnName"].ColumnName = "regnum";
//renaming column in datatable

foreach (DataColumn dtclm in dt_table.Columns) {
    dt_table.Columns[dtclm.ToString()].ColumnName = dt_table.Columns[dtclm.ToString()].ColumnName.ToString().Replace("_"," ");

}

staff_attendance_gridview.Visible = true;
staff_attendance_gridview.DataSource = dt_table;
staff_attendance_gridview.DataBind();
result_message.Text = dt_table.Rows.Count.ToString() + " rows in the table";

aspx文件:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="admin_attendance_.aspx.cs" Inherits="ISMS.admin_attendance" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!--start container box-->
<div id="container_box">  
<div id="text">
<asp:Label runat="server" ID="welcome_message" /><br />
<br />
<!--search bar-->
<p>
<br />
    Employee ID: <asp:TextBox runat="server" ID="employee_search" Text="" /><br />
    <br />
    Attendance ID: <asp:TextBox runat="server" ID="attendance_ID_text_box" Text="" /><br />
    <br />
    fill up both attendance ID and Employee ID and click delete to delete certain record.<br />
    <br />
<asp:Button ID="search_btn" runat="server" Text="search" OnClick="search_btn_Click" />
<asp:Button ID="clock_in_or_out_btn" runat="server" Text="clock in/out" OnClick="clock_in_or_out_btn_Click" />
<asp:Button ID="delete_button" runat="server" Text="delete" OnClick="delete_button_Click" />
    <br />
</p>
<!--gridview-->
   <hr />
    <br />
<div id="gridview">
<asp:GridView runat="server" ID="staff_attendance_gridview" OnPageIndexChanging="gridview_PageIndexChanging" AutoGenerateColumns="true" DataKeyNames="Attendance_id" >
</asp:GridView>



</div>
<!--end gridview-->
<p>
<!--validator-->
<asp:RegularExpressionValidator ID="employee_search_validator" runat="server"     
ErrorMessage="Invalid searching citeria. Only exactly 8 numbers is allowed." 
ControlToValidate="employee_search"
 ValidationExpression="^[0-9]{8}$" /><br />
<br />
</p>
<br />
<!--hyperlink to main menu-->
<asp:Label runat="server" ID="result_message" /><br />
<a href="admin.aspx" >Main menu</a>
</div>    
</div>
<!--end container box-->
</asp:Content>

Database table structure

1 个答案:

答案 0 :(得分:2)

您的GridView中有一个引用列Attendance_id的属性。这必须与列Attendance id的更新名称相匹配。

我已更正下面的代码,以正确处理IDisposable并删除过多的复杂位。

Session["query"] = db.generate_query(parameter1, parameter2, parameter3, parameter4);

using(SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=ISMS;Integrated Security=True"))
{
    using(SqlCommand cmd1 = new SqlCommand(Session["query"].ToString(), conn))
    {
        using(SqlDataAdapter sdal = new SqlDataAdapter(cmd1))
        {
            dt_table = new DataTable();
            sdal.Fill(dt_table);
        }
    }
}

foreach (DataColumn column in dt_table.Columns)
{
    column.ColumnName = column.ColumnName.Replace("_", " " );
}

staff_attendance_gridview.Visible = true;
staff_attendance_gridview.DataSource = dt_table;
staff_attendance_gridview.DataBind();
result_message.Text = dt_table.Rows.Count + " rows in the table";