title: Selecteddatakey always null asp.net gridview
body: <p>I using a gridview that is populated on a rowcommand event of an another data gridview</p>
  
  <p>the problem is when ever I try to use the selecteddatakey property on a selectedchanged event its always gives me the error</p>
  
  <blockquote>
    <p>object refrence not set to an instance of an object</p>
  </blockquote>
  
  <pre><code>cmd1.Parameters.AddWithValue("@busid", GridView2.SelectedDataKey.Value.ToString());
  </code></pre>
  
  <p>I run with debugging and found that the selecteddatakey was null</p>
  
  <p>heres the code I used to populate the gridview</p>
  
  <pre><code>SqlDataSource2.ConnectionString = "Data Source=localhost;Initial Catalog=WCA Database;Integrated Security=True";
                  SqlDataSource2.SelectCommand = "FindAvaliableBuses";
                  SqlDataSource2.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
                  SqlDataSource2.DataBind();
  
                  int index = Convert.ToInt32(e.CommandArgument);
                  string Startdate = GridView1.Rows[index].Cells[3].Text;
                  string DueDate = GridView1.Rows[index].Cells[4].Text;
                  SqlDataSource2.SelectParameters.Add("startdate", Startdate);
                  SqlDataSource2.SelectParameters.Add("duedate", DueDate);
                  SqlDataSource2.SelectParameters.Add("branchId", "11");
                  GridView2.DataSource = SqlDataSource2;
                  GridView2.DataBind();
                  GridView2.DataKeyNames = new string[] {"BusId"};
                  Label1.Text = index.ToString();
  </code></pre>
  
  <p>and here's the code I use for selection:</p>
  
  <pre><code>protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
  {
      SqlConnection con1 = new SqlConnection("Data Source=localhost;Initial Catalog=WCA Database;Integrated Security=True");
      con1.Open();
      SqlCommand cmd1 = new SqlCommand("insert BusAcivity (BusId, ActivityId) values(@busid, @activityid)", con1);
      cmd1.Parameters.AddWithValue("@busid", GridView2.SelectedDataKey.Value.ToString());
      cmd1.Parameters.AddWithValue("@activityid", Label1.Text);
      cmd1.ExecuteNonQuery();
  }
  </code></pre>