从WPF中的代码中添加DataGrid.Columns

时间:2015-08-03 11:56:13

标签: c# wpf xaml datagrid

我有DataGrid来自代码后面的数据绑定我也有2列用于编辑和删除这样

<DataGrid Height="226" HorizontalAlignment="Left" Margin="106,111,0,0" Name="DgEmp" VerticalAlignment="Top" Width="684" ColumnWidth="*" CanUserAddRows="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Actions">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Button Content="Delete" Name="BtnDelete" Click="btnDelete_Click"/>
                        <Button Content="Edit" x:Name="BtnEdit" Click="btnEdit_Click"/>
                    </StackPanel>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

它在前两列中添加按钮。 如何从代码中添加此内容。

我还有另一个困惑,我使用以下方法绑定了我的DataGrid

private void GridBind()
{
    try
    {
        using (var con = new SqlConnection(_conString))
        {
            const string sqlqry = "select ROW_NUMBER() OVER (ORDER BY EmpNo) AS [SlNo],EmpNo,EmpName,Salary,DeptNo from dbo.Employee";
            var cmd = new SqlCommand(sqlqry, con);
            _adapt = new SqlDataAdapter(cmd);
            var dt = new DataTable("Employee");
            _adapt.Fill(dt);
            DgEmp.ItemsSource = dt.DefaultView;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Some error encountered" + ex.Message);
    }
}

此Binding方法无法使用以下 XAML

<DataGrid Height="226" HorizontalAlignment="Left" Margin="106,111,0,0" Name="DgEmp" VerticalAlignment="Top" Width="684" ColumnWidth="*" CanUserAddRows="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="SL No" Width="*"/> 
        <DataGridTextColumn Header="Emp No" Width="*"/>
        <DataGridTextColumn Header="Emp Name" Width="*" />
        <DataGridTextColumn Header="Salary" Width="*" />
        <DataGridTextColumn Header="Dept No" Width="*" />
        <DataGridTemplateColumn Header="Actions">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Button Content="Delete" Name="BtnDelete" Click="btnDelete_Click"/>
                        <Button Content="Edit" x:Name="BtnEdit" Click="btnEdit_Click"/>
                    </StackPanel>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

最后当我尝试删除其clickevent上的记录时,像WinForm一样无法正常工作

 private void btnDelete_Click(object sender, RoutedEventArgs e)
 {
    var id= Convert.ToInt32(DgEmp.Rows[e.RowIndex].Cells[2].Value.ToString()); 
    if(id!=0)
    {
         // Delete query on basis of id
         GridBind();
         ClearData();
     }
}

很抱歉一次提出太多问题,因为这些问题是我面临的问题从WinForm转移到WPF

编辑:我试过这个: 我添加的是

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            GridBind();
            string colProperty = "Name";
            DataGridTextColumn col = new DataGridTextColumn();
            col.Binding = new Binding(colProperty);
            var spHeader = new StackPanel() { Orientation = Orientation.Horizontal };
            spHeader.Children.Add(new TextBlock(new Run(colProperty)));
            Button button1 = new Button();
            button1.Click += btnEdit_Click;
            button1.Content = "Edit";
            spHeader.Children.Add(button1);
            col.Header = spHeader;
            DgEmp.Columns.Add(col);
        }

它看起来像

enter image description here

2 个答案:

答案 0 :(得分:3)

试试第一个问题如何从代码中添加此内容。

var col = new DataGridTemplateColumn {Header = "Actions"};

var dt = new DataTemplate();

var stkpnl = new FrameworkElementFactory(typeof(StackPanel));
stkpnl.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
var btn1 = new FrameworkElementFactory(typeof(Button));

btn1.SetValue(ContentProperty, "Delete");
btn1.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(btnDelete_Click));
btn1.SetValue(MarginProperty, new Thickness(0, 0, 10, 0));
stkpnl.AppendChild(btn1);

var btn2 = new FrameworkElementFactory(typeof(Button));
btn2.SetValue(ContentProperty, "Edit");
btn2.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(btnEdit_Click));
stkpnl.AppendChild(btn2);

dt.VisualTree = stkpnl;
col.CellTemplate = dt;
DgEmp.Columns.Add(col);

对于你的上一个问题当我尝试删除像WinForm这样的clickevent上的记录时它不起作用

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    var drv = DgEmp.SelectedItem as DataRowView;
    if (drv == null) return;
    var empNo = drv[1].ToString(); //getting empno column
    try
    {
        using (var con = new SqlConnection(_conString)) //my connection
        {
            var sqlqry = "delete dbo.Employee where EmpNo='"+empNo+"'";
            con.Open();
            var cmd = new SqlCommand(sqlqry, con);
            cmd.ExecuteNonQuery();
            con.Close();
            GridBind(); //Binding grid after delete
            MessageBox.Show("Data deleted successfully");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

答案 1 :(得分:0)

此处是从代码

后面添加datagrid列的示例代码段
var col = new DataGridTextColumn();
            col.Header = "d";
            col.Binding = new Binding("RoomNumber");
            dataGrid1.Columns.Add(col);

使用这种方法,您可以根据需要添加任意数量的列,并且可以在运行时为每列提供数据绑定,并且可以一次指定itemssource ....

确保在数据网格中标记AutoGenerateColumns="False",以便您可以避免从itemssource添加不需要的列。

编辑按钮

string colProperty = "Name";

DataGridTextColumn col = new DataGridTextColumn();
col.Binding = new Binding(colProperty);
var spHeader = new StackPanel() { Orientation = Orientation.Horizontal };
spHeader.Children.Add(new TextBlock(new Run(colProperty)));
Button button1 = new Button();
button1.Click += Button_Filter_Click;
button1.Content = "Edit";
spHeader.Children.Add(button1);

col.Header = spHeader;

dataGrid.Columns.Add(col);