Я сделал довольно много поисковой системы, чтобы попытаться понять это, но пока не повезло. В основном я надеюсь, что кто-то может ID, почему мой GridView не обновляется, когда я заканчиваю редактирование строки. Я пытался проанализировать пример моего профессора, сделанный в классе, поэтому я могу закончить эту лабораторию, и, насколько я могу судить, я сделал все так же, как и он (за исключением изменения SQL-сервера). Лаборатория не закончила, у меня все еще есть компоненты для добавления, такие как код OnDelete, но ни одно из них не должно быть релевантным вызову обновления.HTML/C# GridView не обновляется после внесения изменений.
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 [email protected]_name, " +
"[email protected], " +
"[email protected]," +
"[email protected], " +
"[email protected], " +
"[email protected] " +
"WHERE [email protected]";
// 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 [email protected]", "@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
Что такое сообщение об ошибке? – CodeNotFound
Сообщение об ошибке отсутствует. Однако, когда я запускаю его, нажмите «Изменить», измените что-то, а затем нажмите «Обновить», он ничего не изменит. Он просто возвращается к тому, что было изначально. –