HTML / C#GridView在进行编辑后未更新

时间:2016-02-14 05:38:31

标签: c# html asp.net gridview sql-update

我做了相当多的谷歌搜索试图弄清楚这一点,但到目前为止没有运气。基本上我希望有人可以在我完成编辑行时识别为什么我的GridView不会更新。我一直试图剖析我的教授在课堂上所做的例子,所以我可以完成这个实验室,并且我可以告诉我已经做了所有事情就像他做的那样(除了更改SQL服务器)。实验室还没有完成,我仍然有要添加的组件,比如OnDelete代码,但是没有什么可以与更新调用相关联。

Default.aspx的:

<%@ Page Title="" Language="C#" MasterPageFile="~/IT213.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphMaster" Runat="Server">
    <h1>
        Edit DB
    </h1>
    <br />
    <asp:gridview runat="server" ID="gvStudents" AutoGenerateColumns="False" HorizontalAlign="Center" AllowSorting="True" OnSorting="gvStudents_Sorting" OnRowEditing="gvStudents_RowEditing" OnRowUpdating="gvStudents_RowUpdating" CellPadding="4" ForeColor="#333333" GridLines="None" DataKeyNames="student">
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:TemplateField HeaderText="Student" SortExpression="student">
                <ItemTemplate>
                    <%# Eval("student") %> <%--This is required to bind the data column to the GridView column.--%>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name" SortExpression="student_name">
                <ItemTemplate>
                    <%# Eval("student_name") %>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtStudentName" Text='<%# Eval("student_name") %>' Columns='<%# getLength(Eval("student_name").ToString()) %>' runat="server"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Address" SortExpression="address">
                <ItemTemplate>
                    <%# Eval("address") %>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtAddress" Text='<%# Eval("address") %>' Columns='<%# getLength(Eval("address").ToString()) %>' runat="server"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City" SortExpression="city">
                <ItemTemplate>
                    <%# Eval("city") %>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtCity" Text='<%# Eval("city") %>' Columns='<%# getLength(Eval("city").ToString()) %>' runat="server"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="State" SortExpression="state">
                <ItemTemplate>
                    <%# Eval("state") %>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtState" Text='<%# Eval("state") %>' Columns='<%# getLength(Eval("state").ToString()) %>' runat="server"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Zip" SortExpression="zip">
                <ItemTemplate>
                    <%# Eval("zip") %>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtZip" Text='<%# Eval("zip") %>' Columns='<%# getLength(Eval("zip").ToString()) %>' runat="server"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Sex" SortExpression="sex">
                <ItemTemplate>
                    <%# Eval("sex") %>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtSex" Text='<%# Eval("sex") %>' Columns='<%# getLength(Eval("sex").ToString()) %>' runat="server"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ShowEditButton="True" />
            <asp:CommandField ShowDeleteButton="True" />
        </Columns>
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />
    </asp:gridview>
</asp:Content>

Default.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    //Check if this is the first page load, if it is bind
    if(!Page.IsPostBack)
    {
        bindStudents();
    }// end IsPostBack
} // end Page_Load

private void bindStudents()
{
    // This sets where gvStudents gets its data, then binds them together.
    gvStudents.DataSource = CMethods.returnTable("SELECT * FROM STUDENTS");
    gvStudents.DataBind();
} // end bindStudents

private void bindStudents(string sort)
{
    // This is the same as bindStudents, but also applies sorting
    gvStudents.DataSource = CMethods.returnTable("SELECT * FROM STUDENTS ORDER BY " + sort);
    gvStudents.DataBind();
} // end bindStudents + sort

protected void gvStudents_Sorting(object sender, GridViewSortEventArgs e)
{
    // This sets the SortExpression used by the GridView
    bindStudents(e.SortExpression);
    Session["sort"] = e.SortExpression;
} // end gvStudents_Sorting

protected void gvStudents_RowEditing(object sender, GridViewEditEventArgs e)
{
    // Determine which row is being edited
    gvStudents.EditIndex = e.NewEditIndex;

    // preserve sort data when editing
    if(Session["sort"] != null)
    {
        bindStudents(Session["sort"].ToString());
    }
    else
    {
        bindStudents();
    }
} // end gvStudents_RowEditing

protected int getLength(string str)
{
    // returns the length of str after triming trailing and leading white space
    return str.Trim().Length;
} // end getLength

protected void gvStudents_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    // Converts Datakey of the row being edited to int16
    int student = Convert.ToInt16(gvStudents.DataKeys[e.RowIndex].Value);

    // Retrieves the text inside the edit TextBoxes and places it in a local TextBox
    TextBox txtStudentName = (TextBox)gvStudents.Rows[e.RowIndex].FindControl("txtStudentName");
    TextBox txtAddress = (TextBox)gvStudents.Rows[e.RowIndex].FindControl("txtAddress");
    TextBox txtCity = (TextBox)gvStudents.Rows[e.RowIndex].FindControl("txtCity");
    TextBox txtState = (TextBox)gvStudents.Rows[e.RowIndex].FindControl("txtState");
    TextBox txtZip = (TextBox)gvStudents.Rows[e.RowIndex].FindControl("txtZip");
    TextBox txtSex = (TextBox)gvStudents.Rows[e.RowIndex].FindControl("txtSex");

    // Stores an SQL statment as string
    string sql = "UPDATE STUDENTS SET student_name=@student_name, " +
                                     "address=@address, " +
                                     "city=@city," +
                                     "state=@state, " +
                                     "zip=@zip, " +
                                     "sex=@sex " +
                                     "WHERE student=@student";

    // Runs previously saved sql statement using assigned parameters
    CMethods.executeNonQuery(sql, "@student_name", txtStudentName.Text.Trim(), "@address", txtAddress.Text.Trim(),
                             "@city", txtCity.Text.Trim(), "@state", txtState.Text.Trim(), "@zip", txtZip.Text.Trim(),
                             "@sex", txtSex.Text.Trim());

    // Closes edit of selected row
    gvStudents.EditIndex = -1;

    // Preserves sort data
    if(Session["sort"] != null)
    {
        bindStudents(Session["sort"].ToString());
    }
    else
    {
        bindStudents();
    }
} // end gvStudents_RowUpdating

//private bool isStudent(int student)
//{
//    // loads table into memory
//    DataTable tbl = CMethods.returnTable("SELECT * FROM STUDENTS WHERE student=@student", "@student", student);
//    // checks if table is empty
//    if(tbl.Rows.Count > 0)
//    {
//        return true;
//    }
//    else
//    {
//        return false;
//    }
//} // end isStudent

CMethods课程:

public static double text2double(string str)
{
    string temp = string.Empty;
    bool blnIsFirstDecimal = true;
    for (int i = 0; i < str.Length; i++)
    {
        if (Char.IsDigit(Convert.ToChar(str.Substring(i, 1))))
        {
            temp += str.Substring(i, 1);
        }
        if (str.Substring(i, 1).Equals("."))
        {
            if (blnIsFirstDecimal)
            {
                blnIsFirstDecimal = false;
                temp += ".";
            }
        }
    } //end for
    if (temp.Trim().Length == 0)
        return 0.0D;
    else
        return Convert.ToDouble(temp);
} // end text2double

public static DataTable returnTable(String CommandText, params Object[] values)
{
    // Creates connection to SQL Database using login info provided via connection string in webconfig
    SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);

    // Creates a new SQL command with the value passed to the method being the command, and a preassigned SQL connection
    SqlCommand sqlCmd = new SqlCommand(CommandText, sqlCon);

    // !!!!!!!!! Not sure why this is here. !!!!!!!!!!!!
    for (int i = 0; i < values.Length; i += 2)
    {
        sqlCmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
    } // end for

    // Creates new dataset, these contain tables and allows you to give those tables IDs.
    DataSet dSet = new DataSet();

    // Used to read/retrieve(?) data from a DB
    SqlDataAdapter dAdapt = new SqlDataAdapter(sqlCmd);

    // Copies rows from source table to DataSet
    dAdapt.Fill(dSet, "tbl");

    return dSet.Tables["tbl"];
} // end returnTable

public static bool executeNonQuery(String CommandText, params Object[] values)
{
    bool bln = true;

    // Creates new sql connection using connection string "Provider"
    SqlConnection con =
        new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);

    // Creates a new SQL command with the value passed to the method being the command, and a preassigned SQL connection
    SqlCommand cmd = new SqlCommand(CommandText, con);

    // !!!!!!!!! Not sure why this is here. !!!!!!!!!!!!
    for (int i = 0; i < values.Length; i += 2)
    {
        cmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
    }
    try
    {
        con.Open(); // opens the previously created sqlconnection
        cmd.ExecuteNonQuery(); // Executes a Transact-SQL statement against the connection, returns number of rows affected
    }
    catch (Exception ex)
    {
        bln = false;
    }
    finally
    {
        con.Close();
    }
    return bln;
} // end executeNonQuery

1 个答案:

答案 0 :(得分:0)

睡眠是美好的事情,所以也是如此。 另一个用户实际上遇到了类似的问题,虽然我昨晚无法找到他的帖子,所以今天早上确实提供了链接。

https://stackoverflow.com/a/13939812/5924307

我错过了一个参数。

错误代码:

CMethods.executeNonQuery(sql, "@student_name", txtStudentName.Text.Trim(), "@address", txtAddress.Text.Trim(),
                             "@city", txtCity.Text.Trim(), "@state", txtState.Text.Trim(), "@zip", txtZip.Text.Trim(),
                             "@sex", txtSex.Text.Trim());

好的代码:

CMethods.executeNonQuery(sql, "@student_name", txtStudentName.Text.Trim(), "@address", txtAddress.Text.Trim(),
                                 "@city", txtCity.Text.Trim(), "@state", txtState.Text.Trim(), "@zip", txtZip.Text.Trim(),
                                 "@sex", txtSex.Text.Trim(), "@student", student);