By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,783 Members | 1,154 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,783 IT Pros & Developers. It's quick & easy.

DataGrid.SelectedIndex is always -1

P: n/a
I have a DataGrid with a command button on the first column of the
DataGrid. The DataGrid is databound to a dataset with DataKeyFiled
bound to "ControlNumber" field in the dataset. I am trying to save the
row's ControlNumber to a page level variable when the corresponding
item command is clicked . However, no matter what I do, the page
property is alway blank.

I also tried use CheckBox in the ItemTemplate. The CheckBox's
AutoPostBack is set to false. Another Command button outside the
DataGrid is used do the postback. Strangely, even I have one box
checked, upon post back the SelectedIndex is always -1.

Does anyone know how to save the "ControlNumber" to the page variable
strControlNumber? Thanks.

The following is the event handler for the DataGrid's OnItemCommand

////////// CodeBehind partial content /////////
public class CustomPaging : System.Web.UI.Page
protected string strControlNumber;
public string ControlNumber
if (strControlNumber == null)
return "no value";
return strControlNumber;
private void MyDataGrid_ItemCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
TableCell CellControlNumber = e.Item.Cells[1];
strControlNumber = CellControlNumber.Text;

private void btnConfirmSelection_Click(object sender, System.EventArgs
strControlNumber = MyDataGrid.SelectedIndex.ToString();

/////////// ASPX partial content /////////
<asp:button id="btnConfirmSelection" runat="server" Text="Confirm
<asp:datagrid id="MyDataGrid" runat="server" CssClass="InventoryTable"
<asp:Checkbox ID="chkSelected" Runat="server"/>
<asp:Button Text="Select" runat="server" />
<HeaderTemplate>Control<br />Number</HeaderTemplate>
<%# DataBinder.Eval(Container.DataItem, "ControlNumber") %>

Nov 19 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.