HTML/C# 网格视图在进行编辑后未更新

本文关键字:编辑 更新 网格 视图 HTML | 更新日期: 2023-09-27 18:34:28

我做了相当多的谷歌搜索来试图解决这个问题,但到目前为止还没有运气。基本上,我希望有人可以确定为什么我的 GridView 在我完成编辑行时没有更新。我一直在尝试剖析我的教授在课堂上所做的示例,以便我可以完成这个实验,并且据我所知,我已经像他一样完成了所有事情(除了更改SQL服务器(。实验室尚未完成,我仍有组件要添加,例如 OnDelete 代码,但缺少的内容都不应与更新调用相关。

默认值.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>

默认值.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

HTML/C# 网格视图在进行编辑后未更新

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

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