在我的编程课上,我刚刚开始使用 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();
}
}
最佳答案
您的 RowUpdating
事件中缺少一些代码。您必须在更新、删除或编辑操作后对网格进行数据绑定(bind),否则您的网格将不会显示正确的数据。
因此,让我们假设您有一个方法可以获取 gridview 的数据,该方法称为 GetMoviesData()
。然后,在 btnSubmit_update_record
方法的末尾,您必须包含以下代码。
MovieResults.EditIndex = -1;
MovieResults.DataSource = GetMoviesData();
MovieResults.DataBind();
关于c# - Gridview,更新功能影响所有行而不是单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47341240/