C#WPF将DataGrid设置为不可编辑模式

时间:2017-10-26 14:26:23

标签: c# wpf datagrid

问题是当我在网格上单击鼠标右键时会破坏应用程序

DataGrid x:Name="dgDbList" AutoGenerateColumns="True" 
ItemsSource="{Binding Mode=OneWay}" IsReadOnly="True" 
EnableRowVirtualization="False"/>

using (SqlCommand myCommand = connection.CreateCommand())
{
    myCommand.CommandType = CommandType.Text;
    myCommand.CommandText = sqlCmd; // here select statement like : select 1 as a, 2 as b union all select 3, 5

    SqlDataReader SqlDataReader = myCommand.ExecuteReader();

    SqlDataAdapter sda = new SqlDataAdapter(myCommand);
    SqlDataReader.Close();

    System.Data.DataTable dt = new System.Data.DataTable();
    sda.Fill(dt);
    grid.ItemsSource = dt.DefaultView;
    grid.AutoGenerateColumns = true;

    grid.CanUserAddRows = false;
    grid.CanUserDeleteRows = false;
    grid.CanUserResizeColumns = false;
    grid.CanUserResizeRows = false;
    grid.CanUserSortColumns = false;
    grid.CanUserReorderColumns = false;
    grid.IsReadOnly = true;

    foreach ( var col in grid.Columns )
    {
        col.IsReadOnly = true;
        col.CanUserReorder = false;
        col.CanUserResize = false;
        col.CanUserSort = false;
    }
}
  

异常:System.ArgumentNullException未处理消息:An   发生了'System.ArgumentNullException'类型的未处理异常   PresentationFramework.dll附加信息:值不能   空。

1 个答案:

答案 0 :(得分:0)

grid.AutoGeneratingColumn += (object sender, DataGridAutoGeneratingColumnEventArgs e) =>
{
    e.Column.IsReadOnly = true;
    e.Column.CanUserReorder = false;
    e.Column.CanUserResize = false;
    e.Column.CanUserSort = false;
};

应该够了。

这只是一个假设,因为您尚未发布完整的堆栈跟踪。我相信你得到异常,因为你试图迭代自动生成列。我建议你使用 AutoGeneratingColumn 事件。

示例:

docker-php-ext-install