I have developed an invoice application and I have added a datagrid control to my WPF application. Now I need to add a textbox into a datagrid cell programatically.
Can you give me some idea about how to find textbox inside CellEditingTemplate? Please refer this screenshot - thanks in advance
UserControltest.xaml
<UserControl x:Class="InvoiceApp.UserControltest" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid x:Name="ItemHolder" Height="30">
</Grid>
</UserControl>
**Mainwindow(FrmBill.xmal):**
<Window x:Class="InvoiceApp.FrmBill"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Testgrid" Height="300" Width="400" Loaded="Window_Loaded">
<Grid>
<VirtualizingStackPanel x:Name="MydataGrid" VerticalAlignment="Stretch" Height="350"/>
<!--Now here i am setting the height to 0,the reason will be explained afterwards-->
</Grid>
</Window>
FrmBill.cs(C# code):
string str = ConfigurationManager.AppSettings["ConnectInvoice"].ToString();
SqlConnection con;
public FrmBill()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
con = new SqlConnection(str);
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tbl_Tax", con);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
UserControltest row = new UserControltest();
int trd = row.ItemHolder.ColumnDefinitions.Count;
if(row.ItemHolder.ColumnDefinitions.Count==0)
{
row.ItemHolder.ColumnDefinitions.Add(new ColumnDefinition());//this will ad required number of columns which will represent the cells
}
TextBox txtbx = new TextBox();
txtbx.Height = 20;
row.ItemHolder.Children.Add(txtbx);
Grid.SetColumn(txtbx,3); /// here 1 is the column count, change it as you want :)
MydataGrid.Children.Add(row);
MydataGrid.Height = MydataGrid.Height + 30;
}
}
As the OP mentioned, he want's to go with a custom
User-control, here's a XAML for a sampleUser-Controlthat may represent aData-Row.Now,let's present it as a
DataGrid.Let's assume the data is coming from a database,then we can use aIDataReaderand also aVirtualizingStackPanelto achieve thedatagridlook:C#
Hope this solves your issue :)