2

I have a DataGrid with data bind from code behind also I have 2 columns for Edit and delete like this

<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>

It add buttons in the 1st two columns. How can I add this from code behind.

Also I have another confusion I bind my DataGrid using the below method

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);
    }
}

This Binding method is not working with the following 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>

And the last when I am trying delete record on its clickevent like WinForm its not working

 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();
     }
}

Sorry for asking too many question at once as these are the problems I am facing shifting from WinForm to WPF.

EDIT : I have tried this: What I have added is

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);
        }

And it looks like

enter image description here

2
  • and you need 2 buttons so better you try adding 2 buttons first and then adding to datagrid. Commented Aug 3, 2015 at 12:47
  • @DeshDeepSingh:That I have already done you can find this in my shared XAML from line no-2 but Buttons should be at the end of data. Commented Aug 3, 2015 at 12:51

2 Answers 2

3

Try this for your 1st question How can I add this from code behind.

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);

For your last question when I am trying delete record on its clickevent like WinForm its not working

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);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks.The first one works fine and the 2nd one deletes the row(not from database).
@SS8:Try this now I have edited my code for delete. And don't forget to accept the answer if that helps you :)
Thanks it worked for me. Now I have accepted your answer.
1

here is sample snippet to add datagrid column from code behind

var col = new DataGridTextColumn();
            col.Header = "d";
            col.Binding = new Binding("RoomNumber");
            dataGrid1.Columns.Add(col);

With this approach you can add as many columns as you want and you can give data binding at run time for each column and you can specify itemssource at once....

make sure to mark AutoGenerateColumns="False" in your data grid so that you can avoid unwanted columns get added from itemssource..

EDIT for Buttons

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);

10 Comments

Yes I have already tried this one and it works fine. But in my case I have taken one column for two buttons(Edit and Delete)
so you want to add buttons everytime
If you want buttons to be added in the columns everytime then in in column add them here through this code only.
try this one for adding buttons this will give you idea I believe now you can implement.
DeshDeepSingh, your answer is fine =) My comment was the recommendation addressed to @SS8
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.