简体   繁体   中英

C# datagrid view wait for selected row

I have ac# form with a function that searches for an item in a sql database, then pops a list of possible results in another window. I want to wait until the user selects a row, then return that result. Everything works as expected, but I can't come up with an efficient way to wait in a loop until the item is selected. Any ideas?

Function to show window:

      // Some sql crap to fill a dataset...//

      Da.Fill(Items, "Items");
      Connection.Close();

      var ItemSearch = new Window1(); // Load new window with a datagrid
      ItemSearch.Show();
      ItemSearch.dataGrid1.ItemsSource = Items.Tables["Items"].DefaultView;
      ItemSearch.dataGrid1.SelectionMode = DataGridSelectionMode.Single;
      ItemSearch.dataGrid1.SelectionUnit = DataGridSelectionUnit.FullRow;

      while (ItemSearch.dataGrid1.SelectedItem != null)
      {
        // Do something until the user selects a row, then return that row
          Thread.Sleep(100); // Doesn't work... Locks whole screen
      }

      }
      return ItemCode; // Selected row

Use ItemSearch.ShowDialog . It will block the subsequent code from running until the form is closed.

And you should set the datagrid1 properties in the form itself. Pass the datasource to the window1 constructor (you should overload the default constructor) :

  var ItemSearch = new Window1(Items.Tables["Items"].DefaultView); 
  ItemSearch.ShowDailog();

Window1 constructor :

public Window1(System.Data.DataView datasource)
  {  
      InitializeComponent();

      dataGrid1.ItemsSource = datasource;
      dataGrid1.SelectionMode = DataGridSelectionMode.Single;
      dataGrid1.SelectionUnit = DataGridSelectionUnit.FullRow;
  }

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