我在listview中有数据访问者。 我的xaml是
<ListView x:Name="listVisitor" ItemsSource="{Binding}" HorizontalAlignment="Left"
Height="582" Margin="110,65,0,0" VerticalAlignment="Top" Width="924"
Grid.ColumnSpan="3" />`
<Button Content="Delete Visitor" Name="Delete" Foreground="white"
HorizontalAlignment="Left" Margin="236,674,0,0" VerticalAlignment="Top"
Width="310" Height="30" Background="#FF1CA0B7" Grid.Column="1"
Click="Delete_Click"/>`
我已经建立了与数据库的连接并创建了删除数据访问者的代码
代码:
private void Delete_Click(object sender, RoutedEventArgs e)`
{
if (listVisitor.SelectedItems.Count > 0)
{
var connectionString = new ConnectionString();
var conn = new SqlConnection(connectionString.ViMS_LOCAL());
DataRowView drv = (DataRowView)listVisitor.SelectedItem;
string visitorno = drv.Row[0].ToString();
conn.Open();
SqlCommand cmd = new SqlCommand("Delete FROM dbo.[Visitor.Profile] Where VisitorNo=@VisitorNo");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("@VisitorNo", visitorno);
cmd.ExecuteNonQuery();
BindData();
}
}
显示错误ExecuteNonQuery:Connection属性尚未初始化。 如何解决这个问题
答案 0 :(得分:2)
在调用Connection
之前,您必须设置SqlCommand
对象的ExectueNonQuery()
属性。例如:
conn.Open()
SqlCommand cmd = new SqlCommand("Delete FROM dbo.[Visitor.Profile] Where VisitorNo=@VisitorNo");
cmd.Parameters.AddWithValue("@VisitorNo", visitorno);
cmd.Connection = conn; // <- Set the connection
cmd.ExecuteNonQuery();
或者你可以在构造函数中传递它:
SqlCommand cmd = new SqlCommand(
"Delete FROM dbo.[Visitor.Profile] Where VisitorNo=@VisitorNo",
conn);