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
js
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
event.

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

private void btnConfirmSelection_Click(object sender, System.EventArgs
e)
{
strControlNumber = MyDataGrid.SelectedIndex.ToString();
Server.Transfer("inventory.aspx");
}

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

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.