我使用填充在另一个数据网格视图的行命令事件上的网格视图
问题是当我尝试在 selectedchanged 事件上使用 selecteddatakey 属性时,它总是给我错误
对象引用未设置为对象的实例
cmd1.Parameters.AddWithValue("@busid", GridView2.SelectedDataKey.Value.ToString());
我运行调试,发现 selecteddatakey 为空
这是我用来填充gridview的代码
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();
这是我用于选择的代码:
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();
}