c# wpf according the textbox value to Dynamically generated the table rows and cloumns code
Here is an example code that creates a table dynamically based on the value entered in a textbox:
XAML code:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Margin="10">
<TextBox x:Name="txtRows" Width="100" Margin="0 0 10 0"/>
<TextBox x:Name="txtCols" Width="100"/>
<Button Click="CreateTable" Content="Create Table" Margin="10 0"/>
</StackPanel>
<ScrollViewer Grid.Row="1">
<Grid x:Name="grid"/>
</ScrollViewer>
</Grid>
</Window>
C# code-behind:
private void CreateTable(object sender, RoutedEventArgs e)
{
int rows, cols;
if (int.TryParse(txtRows.Text, out rows) && int.TryParse(txtCols.Text, out cols))
{
grid.Children.Clear();
grid.RowDefinitions.Clear();
grid.ColumnDefinitions.Clear();
for (int i = 0; i < rows; i++)
{
grid.RowDefinitions.Add(new RowDefinition());
}
for (int i = 0; i < cols; i++)
{
grid.ColumnDefinitions.Add(new ColumnDefinition());
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Border border = new Border();
border.BorderBrush = Brushes.Black;
border.BorderThickness = new Thickness(1);
Grid.SetRow(border, i);
Grid.SetColumn(border, j);
grid.Children.Add(border);
}
}
}
}
This code creates a table with the number of rows and columns specified in the textboxes. It first clears any existing rows and columns from the grid, then adds new ones based on the input values. Finally, it creates a border element for each cell in the table and adds it to the grid.
原文地址: https://www.cveoy.top/t/topic/bVQa 著作权归作者所有。请勿转载和采集!