我正在从列表视图中删除单个数据库记录,删除后我尝试使用listView1.selectedindex属性在listview中导航,但我注意到它突出显示了错误的记录(例如我将listView1.selectedindex设置为1但它显示的索引为0)。怎么了?请帮忙!
protected void deleteButton_Click(object sender, EventArgs e)
{
int id = int.Parse(((Label)ListView1.Items[ListView1.SelectedIndex].FindControl("idLabel")).Text);
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = @id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("@id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
BindDataFromBaseToListView方法看起来如此:
private void BindDataFromBaseToListView()
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("select * from Employee", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
ListView1.DataSourceID = null;
ListView1.DataSource = dTable;
ListView1.DataBind();
}
conn.Close();
}
答案 0 :(得分:0)
您可以使用ListView的deleteButton_Click
事件来获取所选的行值,而不是使用OnItemCommand
事件,并删除您想要的项目,如下面的代码:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
int id = 0;
if(int.TryParse((e.Item.FindControl("idLabel") as Label).Text, out id))
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = @id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("@id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
}
}
在你的控制元素上看起来像这样:
<asp:ListView ID="ListView1" runat="server" OnItemCommand="ListView1_ItemCommand" .. >
...
<ItemTemplate>
<asp:Button runat="server" CommandName="delete" Text="Delete" ID="DeleteButton" />
...
如果您仍然遇到问题,请告诉我。