简体   繁体   English

WPF Datagrid自动增量列生成错误的值?

[英]Wpf datagrid auto-increment column generating wrong values?

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. 嗨,我正在一个简单的WPF应用程序上工作。我的问题是我想包括序列号(S_No)列,该列应自动递增,但显示异常值。 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: XAML是:

<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 : 捕捉是: 在此处输入图片说明

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM