解析DataGrid.SelectedItems时绑定到的对象类型(绑定到MySql DataTable)

时间:2015-06-28 21:41:38

标签: c# wpf datagrid datatable

我有一个简单的C# / WPF应用程序,它将MySql数据库读入DataGrid。

<DataGrid  Height="470" Width="800" AutoGenerateColumns="True" CanUserResizeColumns="True" CanUserReorderColumns="True" x:Name="DgrReadWrite" ItemsSource="{Binding ''}"  HorizontalAlignment="Center" VerticalAlignment="Center" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" />

我将Sql数据加载到其中:

string connStr = Service.getConnectionString();

string sql = "SELECT * FROM adat";
try
{
    MySqlConnection connection = new MySqlConnection(connStr);
    MySqlCommand cmdSel = new MySqlCommand(sql, connection);

    MySqlDataAdapter da2 = new MySqlDataAdapter(cmdSel);
    da2.Fill(this.dt2);
    DgrReadWrite.DataContext = dt2;
}
catch (Exception ex)
{
    MessageBox.Show("MySQL kapcsolódási hiba!", "Hiba!", MessageBoxButton.OK, MessageBoxImage.Error);
}

当我按下删除按钮时,会发生这种情况:

for (int i = 0; i < this.dt2.Rows.Count; i++)
{

    // looping through DgrReadWrite.SelectedItems.Cast<SomethingReadable??>
    if (somethingReadable[0] == this.dt2.Rows[i][0].ToString())
    {
        dt2.Rows[i].Delete();
        DgrReadWrite.Items.Refresh();
    }
}

我的问题:我应该选择什么类型的所选项目,以便我可以在方法中理解它们?提前谢谢。

1 个答案:

答案 0 :(得分:1)

使用DataRowView解析数据很容易。

 foreach (DataRowView drRow in DgrReadWrite.SelectedItems)
            {
                listOfRowsToDelete.Add(drRow.Row);
                // put index numbers into a string for MySQL query
                ids = ids + drRow["index"] + ",";
            }