Thursday 15 December 2011

Best Example found on MSDN help Using GridView in ASP.net and its properties

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:Button ID="CheckAll" runat="server" Text="Check All" OnClick="CheckAll_Click" />
<asp:Button ID="UncheckAll" runat="server" Text="Uncheck All" OnClick="UncheckAll_Click" />
<asp:GridView ID="Products" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"DataSourceID="ProductsDataSource" AllowPaging="True" EnableViewState="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ProductSelector" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductName" HeaderText="Product" SortExpression="ProductName" />
<asp:BoundField DataField="CategoryName" HeaderText="Category" ReadOnly="True" SortExpression="CategoryName" />
<asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HeaderText="Price"HtmlEncode="False" SortExpression="UnitPrice" /></Columns></asp:GridView>
<asp:ObjectDataSource ID="ProductsDataSource" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetProducts" TypeName="ProductsBLL"> </asp:ObjectDataSource>
<asp:Button ID="DeleteSelectedProducts" runat="server" Text="Delete Selected Products" OnClick="DeleteSelectedProducts_Click" />
<asp:Label ID="DeleteResults" runat="server" EnableViewState="False" Visible="False"></asp:Label></asp:Content>

protected void DeleteSelectedProducts_Click(object sender, EventArgs e)
{
bool atLeastOneRowDeleted = false;

// Iterate through the Products.Rows property
foreach (GridViewRow row in Products.Rows)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("ProductSelector");
if (cb != null && cb.Checked)
{
// Delete row! (Well, not really...)
atLeastOneRowDeleted = true;

// First, get the ProductID for the selected row
int productID = Convert.ToInt32(Products.DataKeys[row.RowIndex].Value);

// "Delete" the row
DeleteResults.Text += string.Format("This would have deleted ProductID {0}<br />", productID);

//... To actually delete the product, use ...
//ProductsBLL productAPI = new ProductsBLL();
//productAPI.DeleteProduct(productID);
//............................................
}//end if
}//end for

// Show the Label if at least one row was deleted...
DeleteResults.Visible = atLeastOneRowDeleted;
}//end function

No comments:

Post a Comment