Visual Studio 2013填充DataGrid

时间:2014-01-20 15:28:34

标签: c# wpf sqlite datagrid

我正在尝试从SQLite数据库中读取数据。然后我想将它填入我的DataGrid,但以下代码不起作用( dataUrl是DataGrid-Object ):

    string sql = "SELECT rowid, url FROM urls WHERE url LIKE '%@search%'";
    SQLiteConnection myConnection = new SQLiteConnection(@"Data Source=C:\URL Store\URL Store\bin\Release\urlStore.sqlite;Version=3;Password=*censored*;");
    SQLiteCommand command = new SQLiteCommand(sql, myConnection);
    command.Parameters.AddWithValue("@search", txtSearch.Text);
    myConnection.Open();
    command.ExecuteNonQuery();
    SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
    DataSet set = new DataSet();
    try
    {
        //            
        //ESPECIALLY THIS PART IS IMPORTANT TO ME
        //
        adapter.Fill(set);
        DataTable table = set.Tables[0];
        dataUrl.DataContext = table;
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error loading data!");
    }

它甚至不会抛出异常。

1 个答案:

答案 0 :(得分:3)

您应该设置ItemsSource而不是DataContext,为此您需要DataView,因为它只接受IEnumerable

dataUrl.ItemsSource = table.DefaultView;

dataUrl.ItemsSource = new DataView(table);

同时删除command.ExecuteNonQuery();

  

您可以使用ExecuteNonQuery执行目录操作(例如,查询数据库的结构或创建数据库对象,例如表),或者通过执行UPDATE,INSERT或更改数据库而不使用DataSet来更改数据DELETE语句。

另外,因为您使用参数和AddWithValue(..),所以您的查询应如下所示:

string sql = "SELECT rowid, url FROM urls WHERE url LIKE @search";

然后添加这样的参数:

command.Parameters.AddWithValue("@search", "%" + txtSearch.Text + "%");

这是使用参数

的重点