title: How to set selected item of a DataGrid programmatically in WPF with MVVM application?
body: <p>I have bound the <code>DataTable</code> to the <code>DataGrid</code> control. How can I set the selected item <strong>programmatically</strong> ?</p>
  
  <blockquote>
    <p>Example</p>
  </blockquote>
  
  <p>In my <code>view model</code> I have a property of type DataTable to bind the DataGrid</p>
  
  <pre class="lang-cs prettyprint-override"><code> private DataTable sizeQuantityTable;
  
   public DataTable SizeQuantityTable
   {
          get
          {
              return sizeQuantityTable;
          }
          set
          {
              sizeQuantityTable = value;
              NotifyPropertyChanged("SizeQuantityTable");
          }
    }
  </code></pre>
  
  <p>My <code>XAML</code></p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;DataGrid 
              ItemsSource="{Binding SizeQuantityTable}"
              AutoGenerateColumns="True" 
              Margin="0,0,0,120" /&gt;
  </code></pre>
  
  <p>The <code>constructor</code> of the view model (assigning dummy values)</p>
  
  <pre class="lang-cs prettyprint-override"><code>this.SizeQuantityTable = new DataTable();
  
  DataColumn sizeQuantityColumn = new DataColumn();
  sizeQuantityColumn.ColumnName = "Size Quantity";
  this.SizeQuantityTable.Columns.Add(sizeQuantityColumn);
  
  DataColumn sColumn = new DataColumn();
  sColumn.ColumnName = "S";
  this.SizeQuantityTable.Columns.Add(sColumn);
  
  DataColumn mColumn = new DataColumn();
  mColumn.ColumnName = "M";
  this.SizeQuantityTable.Columns.Add(mColumn);
  
  DataRow row1 = this.SizeQuantityTable.NewRow();
  row1[sizeQuantityColumn] = "Blue";
  row1[sColumn] = "12";
  row1[mColumn] = "15";
  this.SizeQuantityTable.Rows.Add(row1);
  
  DataRow row2 = this.SizeQuantityTable.NewRow();
  row2[sizeQuantityColumn] = "Red";
  row2[sColumn] = "18";
  row2[mColumn] = "21";
  this.SizeQuantityTable.Rows.Add(row2);
  
  DataRow row3 = this.SizeQuantityTable.NewRow();
  row3[sizeQuantityColumn] = "Green";
  row3[sColumn] = "24";
  row3[mColumn] = "27";
  this.SizeQuantityTable.Rows.Add(row3);
  </code></pre>
  
  <p>OK. I have created three columns namely <code>sizeQuantityColumn</code>, <code>sColumn</code> and <code>mColumn</code> and added three rows namely <code>row1</code>, <code>row2</code> and <code>row2</code>. </p>
  
  <p>So, Let's say I wanna set the selected item as <code>row2</code> (So in the view, the second row should be highlighted). </p>
  
  <p>How can I do this?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I hardcoded the <code>SelectedIndex</code> of the DataGrid to 1. (So the second row should be selected). In <code>design time</code> it shows as selected. But not in the run time. You can see it in the below snapshot. </p>
  
  <p>So ultimaltely the problem is <strong>Not highlighting</strong> the row.</p>
  
  <p><img src="https://i.stack.imgur.com/Foc0a.png" alt="enter image description here"></p>