Monday, May 24, 2010

Delete record with datagrid?

i use asp.net(1.1)(c#) - i want to delete a record from database with using check box at datagrid(like yahoo).is there any control to add check box in datagrid or is there any way to do that.


if there is'nt please give me a javascript code to delete record with confirm box.


THANKS

Delete record with datagrid?
Of course there is a way to do it!


To add a control to a column in your DataGrid, you have to use a TemplateColumn like in the following DataGrid:





%26lt;asp:datagrid id="dg" runat="server" Width="100%"


AutoGenerateColumns="False" %26gt;


%26lt;Columns%26gt;


%26lt;asp:BoundColum DataField="ID" /%26gt;


%26lt;asp:TemplateColumn%26gt;


%26lt;ItemTemplate%26gt;


%26lt;asp:CheckBox id="chk" runat="server"


AutoPostBack="false" /%26gt;


%26lt;/ItemTemplate%26gt;


%26lt;/asp:TemplateColumn%26gt;


%26lt;/Columns%26gt;


%26lt;/asp:datagrid%26gt;





Let's assume when a user hits a Delete Button, you want to delete all records which are selected. In the Event Handler for the Delete Button use the following code to loop through the Grid Items:





foreach(DataGridItem item in dg.Items)


{


if((item.ItemType == ListItemType.Item) ||


(item.ItemType == ListItemType.AlternatingItem))


{


CheckBox chkBox;


chkBox = (CheckBox)(item.FindControl


("chkPublished"));


if(chkBox.Checked)


{


//get ID of Item from Grid (first column is the ID)


int ItemID = int.Parse(item.Cells[0].Text);


//now use the Item ID to do some action on the


//Item like deleting it from DB


}


}


}
Reply:One way to do it is create a template column with a checkbox and a hidden label to store the id for each record. And then in your code behind for your delete button have a loop that goes through and gets the ids and concatenates them and creates your delete sql. Here is an article that explains it better than I can.


http://www.dotnetjunkies.com/Tutorial/17...

forsythia

No comments:

Post a Comment