简体   繁体   中英

WPF DataGrid select first row

I am using a TabControl and a DataGrid on each tab.

Only the first Tab shows the first row automatically. Each DataGrid is filled with a binding with SQL. When the DataGrid is empty, or when a field is not selected and the select button is clicked, then the program crashes.

IsSynchronized = on
SelectionMode = Extended
SelectionUnit = FullRow

I need the right statement for the select button. This is my code:

    private void Btn1_Click(object sender, RoutedEventArgs e)
    {
        var DG1 = dg1.SelectedCells[0];
        var cellInfor = dg1.SelectedCells[0];
        dg1.CurrentCell = new DataGridCellInfo(dg1.Items[0], dg1.Columns[0]);
        var DG11 = (cellInfor.Column.GetCellContent(cellInfor.Item) as TextBlock).Text;

        if (dg1 == null || dg1.CurrentCell == null)
        {
            MessageBox.Show("there is no recorid selected");
                return;
        }
    }

    private void Btn2_Click(object sender, RoutedEventArgs e)
    {
        var DG2 = dg2.SelectedItems[0].ToString();

        if (DG2.Items[0].ToString() == null || DG2.SelectedItem[0] == null)
        {
            MessageBox.Show("There is no RecID number selected", "Error");
            return;
        }


        int RecID = Convert.ToInt32(DG22);
        //this.AptzClearControls();
        //this.GetAptzRecipe(RecID);
        //this.DisplayAptzRecipe();

DG22 at the end? You probably need DG2. You can also use try{} catch{} for this button..

if (DG2.Items[0].ToString() != null && DG2.SelectedItem[0] != null)
        {
        int RecID = Convert.ToInt32(DG2);
        }
else 
{
MessageBox.Show("There is no RecID number selected", "Error");
return;
}

=====================Edited=========== I am not sure what you are trying to do.. You need to get row/column of selected cell?
Take a look at this page: Microsoft manual .

You need something like that:

private void selectedCellsButton_Click(object sender, System.EventArgs e)
{
    Int32 selectedCellCount =
        dataGridView1.GetCellCount(DataGridViewElementStates.Selected);
    if (selectedCellCount > 0)
    {
            for (int i = 0; i < selectedCellCount; i++)
            {
                (dataGridView1.SelectedCells[i].RowIndex.ToString());
                (dataGridView1.SelectedCells[i].ColumnIndex.ToString());
            }

        }
    }
}

I have come to getting the cell, if a row is selected. If not, the program crashes. How can I stop the program. I used an if statement but it will not stop the program if nothing is selected and the program crashes.

    private void Btn2_Click(object sender, RoutedEventArgs e)
    {

        var DG2 = dg1.SelectedCells[0];

        if (DG2 == null || dg2.CurrentCell == null)
        {
            MessageBox.Show("there is no recorid selected");
            return;
        }

        var cellInfor = dg2.SelectedCells[0];
        dg2.CurrentCell = new DataGridCellInfo(dg2.Items[0], dg2.Columns[0]);
        var DG22 = (cellInfor.Column.GetCellContent(cellInfor.Item) as TextBlock).Text;

        MessageBox.Show(DG22);
                 int AddID = Convert.ToInt32(DG22);   
    }

To always have a row selected. Settings, SelectionMode += Extended, SelectionUnit = FullRow Can user add rows = False, Auto generating Column header = False. For dat I used Binding to SQL database. MainWindow.xaml I added DataGridTextColumn Binding and Header name. In MainWindow>xaml.cs I selected first cell for data AddID. I hope this helps others.

        <TabItem x:Name="tab2" Header="tab2">
            <Grid Background="#FFE5E5E5" DataContext="{StaticResource addTableViewSource}" >
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <DataGrid x:Name="dg2" HorizontalAlignment="Left" Height="136" Margin="34,29,0,0" VerticalAlignment="Top" Width="500"
                          ItemsSource="{Binding}" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" AutoGenerateColumns="False" CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserSortColumns="True" RenderTransformOrigin="0.529,0.412" AutomationProperties.IsColumnHeader="True">
                    <DataGrid.Columns>
                        <DataGridTextColumn Binding="{Binding AddID}" Header="AddID" Foreground="#FFBF0E0E"/>
                        <DataGridTextColumn Binding="{Binding FName}" Header="FName"/>
                        <DataGridTextColumn Binding="{Binding LName}" Header="LName"/>
                        <DataGridTextColumn Binding="{Binding Street}" Header="Street" Foreground="#FF18904F"/>
                        <DataGridTextColumn Binding="{Binding City}" Header="City"/>
                        <DataGridTextColumn Binding="{Binding State}" Header="State"/>
                        <DataGridTextColumn Binding="{Binding Zip}" Header="Zip"/>

                    </DataGrid.Columns>

                </DataGrid>

                <Button x:Name="btn2" Content="Button" HorizontalAlignment="Left" Margin="273,185,0,0" VerticalAlignment="Top" Width="75" Click="Btn2_Click" RenderTransformOrigin="-2.084,4.366"/>
            </Grid>
        </TabItem>

    private void Btn2_Click(object sender, RoutedEventArgs e)
    {
        var DG2 = dg2.SelectedCells[0]; 
        var cellInfor = dg2.SelectedCells[0];
        dg2.CurrentCell = new DataGridCellInfo(dg2.Items[0], dg2.Columns[0]);
        var DG22 = (cellInfor.Column.GetCellContent(cellInfor.Item) as TextBlock).Text;

        MessageBox.Show(DG22);

         int AddID = Convert.ToInt32(DG22);

Update to the above result. If the DataGrid is empty, this if statement stops the program from ending.

    private void Btn2_Click(object sender, RoutedEventArgs e)
    {
        if (dg2.SelectedIndex == -1)
        {
            MessageBox.Show("There is no recipe selected", "Error");
            return;
        }

        var DG2 = dg2.SelectedCells[0]; 
        var cellInfor = dg2.SelectedCells[0];
        dg2.CurrentCell = new DataGridCellInfo(dg2.Items[0], dg2.Columns[0]);
        var DG22 = (cellInfor.Column.GetCellContent(cellInfor.Item) as TextBlock).Text;

        MessageBox.Show(DG22);

         int AddID = Convert.ToInt32(DG22);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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