I have this requirement for the Master-Detail page with GridView/DetailView: By default, the GridView should have the first row seleted, and DetailView showing information for that row.
So I have a GridView control gdvScheduleList and a DetailView control dtvScheduleDetail. The data source for ScheduleDetail is called SqlDataSourceScheduleDetail. The parameter of SqlDataSourceScheduleDetail is “ScheduleId“.
Here is the even handler for the GridView gdvScheduleList's DataBound event, which will be fired up after the GridView has finished databind.
protected void On_gdvScheduleList_DataBound(object sender, EventArgs e)
{
if (null != gdvScheduleList.SelectedDataKey)
{
SqlDataSourceScheduleDetail.SelectParameters["ScheduleId"].DefaultValue = gdvScheduleList.SelectedDataKey.Value.ToString();
}
}
As you can see, SelectedDataKey peroperty of GridView gdvScheduleList is the place you can get the Key parameter for DetailView's data source control SqlDataSourceScheduleDetail. But by defualt, it's Null! Why? because you are not selecting any row in the GridView by default.
The answer is the SelectedIndex property of the GridView control. By default, it has value “-1”. Once I set it to “0”, it worked like a dream.