DataGrid.SelectedIndex is always -1

J

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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top