【发布时间】:2017-11-17 00:08:42
【问题描述】:
对于我的编程课,我刚开始将 GridView 用于电影数据库表,现在我正在实现编辑、更新和删除功能。我得到了编辑和更新,但更新给我带来了麻烦。
当我单击更新时,我的所有行都更新为相同的内容(例如:我编辑电影标题并且所有行都更改为相同的电影标题)。我不确定我的标签是否混淆了。
我的数据库表: 注意:我也是我使用的代码是类中的示例,类中的示例有效,但由于某种原因我的没有。
下面是我的代码示例。
<asp:GridView runat="server" ID="MovieResults" Wrap="true" Visible="false" AutoGenerateColumns="false"
OnRowEditing="btnSubmit_Click_one" OnRowUpdating="btnSubmit_update_record"
DataKeyNames="MovieID" OnRowDeleting="btnSubmit_delete_record">
<Columns>
<asp:BoundField DataField="MovieTitle" HeaderText="Movie" />
<asp:BoundField DataField="DateChecked" HeaderText="Date Checked" />
<asp:BoundField DataField="CheckedOut" HeaderText="Checked Out" />
<asp:BoundField DataField="MovieDescription" HeaderText="Description" />
<asp:ImageField DataImageUrlField="ImageLocation" ControlStyle-Width="50"
ControlStyle-Height = "50" HeaderText = "Movie Image" />
<asp:CommandField ShowEditButton="true" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
cs文件
public void btnSubmit_update_record(Object Src, GridViewUpdateEventArgs e)
{
get_connection();
try
{
int id = int.Parse(MovieResults.DataKeys[e.RowIndex].Value.ToString());
connection.Open();
command = new SqlCommand("UPDATE content SET MovieTitle=@MovieTitle, MovieDescription=@MovieDescription WHERE TRUE", connection);
//command.Parameters.AddWithValue("@MovieID",
//((TextBox)MovieResults.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString());
command.Parameters.AddWithValue("@MovieTitle",
((TextBox)MovieResults.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString());
command.Parameters.AddWithValue("@MovieDescription",
((TextBox)MovieResults.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString());
command.ExecuteNonQuery();
}
catch (Exception err)
{
// Handle an error by displaying the information.
lblInfo.Text = "Error reading the database. ";
lblInfo.Text += err.Message;
}
finally
{
// Either way, make sure the connection is properly closed.
// (Even if the connection wasn't opened successfully,
// calling Close() won't cause an error.)
connection.Close();
lblInfo.Text += "<br /><b>Update was successfull</b> ";
lblInfo.Text += connection.State.ToString();
}
}
【问题讨论】:
-
您可能想查看更新查询中的
WHERE子句。