문제

Hi i am working on a simple wpf application .My issue is i want to include serial number(S_No) column which should be auto incremented but it is showing abnormal values. I want proper serial column as my first column. My code is :

public partial class MainWindow : Window
    {
        public ObservableCollection<VLANS> vlan { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            vlan=new ObservableCollection<VLANS>();
            this.DataContext=this;



            dg.ItemsSource =vlan;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var serial = new VLANS();
            serial.S_No = vlan.Count;
            vlan.Add(serial);

            var vname = new VLANS();
            vname.VlanName = t1.Text;
            vlan.Add(vname);



        }
    }

    public class VLANS
    {
        public string VlanName { get; set; }
        public int S_No { get; set; }
    }
}

XAML is:

<Window x:Class="TextboxToDatagridTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="200"/>
        </Grid.RowDefinitions>
        <TextBox
            Name="t1"
            Grid.Row="0"
            Width="150"
            Height="50"
            Margin="200,0,0,0"
            />
        <Button
            Grid.Row="0"
            Width="150"
            Height="40"
            Content="Button" FontSize="25"
            HorizontalAlignment="Left"
            Margin="80,0,0,0" Click="Button_Click">
         </Button>
        <DataGrid
            AutoGenerateColumns="False"
            Name="dg"
            Grid.Row="1">
            <DataGrid.Columns >
                <DataGridTextColumn Header="S.No" Binding="{Binding Path=S_No}" />
                <DataGridTextColumn Header="Vlan Name" Binding="{Binding Path=VlanName}"/>

            </DataGrid.Columns>

        </DataGrid>  

    </Grid>
</Window>

Snap is : enter image description here

Can anyone tell me where i am mistaking. Any help would be highly praised.

도움이 되었습니까?

해결책

The problem is with your event handler instead of what you have try this

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var serial = new VLANS();
        vlan.Add(serial)
        serial.S_No = vlan.Count;
        serial.VlanName = t1.Text;
        vlan.Add(serial);

    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top