我的GridView出了问题。当我尝试编辑GridView时,我只返回旧的值。
这是RowUpdating事件:
protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox nVorname = (TextBox)row.FindControl("newVorname");
TextBox nNachname = (TextBox)row.FindControl("newNachname");
TextBox nTelnr = (TextBox)row.FindControl("newTelnr");
TextBox nEmail = (TextBox)row.FindControl("newEmail");
HiddenField tid = (HiddenField)row.FindControl("id");
grid.EditIndex = -1;
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlCommand cmd = new SqlCommand("update dasOertliche set vorname= @vorname, nachname=@nachname, telefonnr =@telnr, email =@email where id = @id", sqlConn);
cmd.Parameters.Add("@vorname", SqlDbType.VarChar);
cmd.Parameters["@vorname"].Value = nVorname;
cmd.Parameters.Add("@nachname", SqlDbType.VarChar);
cmd.Parameters["@nachname"].Value = nNachname.Text;
cmd.Parameters.Add("@email", SqlDbType.VarChar);
cmd.Parameters["@email"].Value = nEmail.Text;
cmd.Parameters.Add("@telnr", SqlDbType.VarChar);
cmd.Parameters["@telnr"].Value = nTelnr.Text;
cmd.Parameters.Add("@id", SqlDbType.Int);
cmd.Parameters["@id"].Value = tid.Value;
cmd.ExecuteNonQuery();
sqlConn.Close();
bind();
}
.aspx中的TemplateField:
<Columns>
<asp:TemplateField HeaderText = "Vorname">
<ItemTemplate> <%#Eval ("vorname") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="newVorname" runat="server" Text='<%#Eval ("vorname") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</columns>
我的GridView代码:
<asp:GridView runat="server" ID="grid" BorderWidth="0px" CellPadding="10"
CellSpacing="10" HorizontalAlign="Center" AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True" onrowcancelingedit="grid_RowCancelingEdit"
onrowediting="grid_RowEditing" onrowupdating="grid_RowUpdating"
AutoGenerateColumns="False">
就像我说的,它总是返回旧值。有什么建议吗?
我的Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
我的绑定():
public void bind()
{
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlDataAdapter sqlComm = new SqlDataAdapter("SELECT id, vorname AS 'Vorname', nachname AS 'Nachname', telefonnr, email AS 'E-Mail' FROM dasOertliche ORDER BY nachname ASC", sqlConn);
DataSet ds = new DataSet();
sqlComm.Fill(ds, "dasOertliche");
grid.DataSource = ds.Tables[0];
grid.DataBind();
sqlConn.Close();
}
答案 0 :(得分:4)
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
错了。
应该是:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}
答案 1 :(得分:1)
您最后需要致电GridView1.DataBind()
。
答案 2 :(得分:1)
On Page Load将绑定网格代码置于以下条件
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}