Edit Gridview Row ASP.net - c#

Struggling to edit a Gridview Row. Once I hit edit the gridview disappears, I guess because I only bind the grid on !IsPostBack - although the tutorial tells me to do it this way.
I have tried rebinding on postback which lets me edit the gridview but keeps the default values - not the new values.
Any help appreciated.
if (!IsPostBack)
{
if (Session["Order_ID"] != null)
{
showgrid(int.Parse(Session["Order_ID"].ToString()));
}
}
public void showgrid(int Order_ID)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDbConn"].ToString());
string sqlstring = "Removed - is working";
SqlCommand cmd = new SqlCommand(sqlstring, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gv_ExistingAds.DataSource = ds;
gv_ExistingAds.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
gv_ExistingAds.EditIndex = e.NewEditIndex;
showgrid(int.Parse(Session["Order_ID"].ToString()));
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lb = (Label)gv_ExistingAds.Rows[e.RowIndex].FindControl("Label3");
TextBox tx1 = (TextBox)gv_ExistingAds.Rows[e.RowIndex].FindControl("TextBox3");
string tx11 = tx1.Text;
gv_ExistingAds.EditIndex = -1;
showgrid(int.Parse(Session["Order_ID"].ToString()));
}
HTML
<asp:GridView runat="server" AutoGenerateColumns="false" ShowFooter="True" ShowHeaderWhenEmpty="false" EmptyDataText="This order has no ads..."
ID="gv_ExistingAds" CssClass="table table-striped table-bordered table-hover"
Visible="true" DataKeyNames="Orders_Editions_ID, Cancelled, Order_ID" EnableViewState="true" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:BoundField HeaderText="Publication Title" HtmlEncode="false" DataField="Publication_Title" />
<asp:BoundField HeaderText="Insertion Date" HtmlEncode="false" DataField="Insertion_Date" />
<asp:BoundField HeaderText="Advert Type" HtmlEncode="false" DataField="Description" />
<asp:BoundField DataField="Ad_Size" HeaderText="Size" ItemStyle-Width="150" />
<asp:BoundField DataField="Position" HeaderText="Position" ItemStyle-Width="150" />
<asp:BoundField DataField="Revenue" HeaderText="Revenue" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Note" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Note") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("Note") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="btnedit" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnupdate" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="btncancel" runat="server" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemStyle Width="165px" />
<ItemTemplate>
<%--<asp:LinkButton ID="btn_UpdateAdvert" ControlStyle-CssClass="btn btn-primary btn-xs" CommandName="Update_Advert" CommandArgument='<%#Eval("Orders_Editions_ID")%>' runat="server" Text="Update" CausesValidation="false" />--%>
<asp:LinkButton ID="btn_CancelAdvert" ControlStyle-CssClass="btn btn-warning btn-xs" CommandName="Cancel_Advert" CommandArgument='<%#Eval("Orders_Editions_ID")%>' runat="server" Text="Cancel" CausesValidation="false" />
<asp:LinkButton ID="btn_DeleteAdvert" ControlStyle-CssClass="btn btn-danger btn-xs" CommandName="Delete_Advert" CommandArgument='<%#Eval("Orders_Editions_ID")%>' runat="server" Text="Delete" CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#FF6699" />
</asp:GridView>

Related

On Gridview RowCommand button text is not getting changed in ASP.NET using C#

I want to update the text of the btn_Update which is inside the EditTemplate of gridview. For that I wrote the code shown here. But the text is still shown as Reject, even if I am trying to update the text to Approve.
Here's my markup and code:
<asp:GridView ID="rptHotoIPDataInfo" runat="server" AutoGenerateColumns="False" CssClass="table table-bordered nowrap tblrptHotoIPDataInfo"
AllowPaging="True" PageSize="20" OnPageIndexChanging="rptHotoIPDataInfo_PageIndexChanging"
DataKeyNames="SAP_ID" OnRowEditing="rptHotoIPDataInfo_RowEditing" OnRowUpdating="rptHotoIPDataInfo_RowUpdating"
OnRowCancelingEdit="rptHotoIPDataInfo_RowCancelingEdit" OnRowDataBound="rptHotoIPDataInfo_RowDataBound"
OnRowCommand="rptHotoIPDataInfo_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Approved / Reject" ItemStyle-Width="80px"> <%--"Accepted/Rejected (By default checked means approved)"--%>
<ItemTemplate >
<asp:CheckBox ID="chkRow" runat="server" Checked="true" Width="5px" OnCheckedChanged="chkRow_CheckedChanged"
AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-Width="120px">
<ItemTemplate>
<asp:Button ID="btn_Edit" runat="server" Text="Reject" CommandName="Edit" Enabled="false" CssClass="btn btn-blue" CommandArgument="<%# Container.DataItemIndex %>" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" runat="server" Text="Reject" CommandName="Update" CssClass="btn btn-blue" />
<asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel" CssClass="btn btn-blue" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rejected Remarks" ItemStyle-Width="150px">
<ItemTemplate>
<asp:Label ID="lblRemarks" runat="server" Text='<%#Eval("REJECT_REMARKS") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRemarks" runat="server" Text='<%#Eval("REJECT_REMARKS") %>' Width="150px" CssClass="form-control"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" ItemStyle-Width="50px">
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SAP_ID" HeaderText="SAP ID">
<ItemStyle CssClass="labelbold" Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="CR_NO" HeaderText="Description" Visible="False">
<ItemStyle CssClass="labelbold" Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="R4GSTATE_CODE" HeaderText="State Code">
<ItemStyle CssClass="labelbold" Width="30px" />
</asp:BoundField>
<asp:BoundField DataField="HOTO_STATUS" HeaderText="Hoto Status">
<ItemStyle CssClass="labelbold" Width="50px" />
</asp:BoundField>
<asp:BoundField DataField="CR_Justifications" HeaderText="CR Justifications">
<ItemStyle CssClass="labelbold" Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="APPROVE_REJECT" HeaderText="Status">
<ItemStyle CssClass="labelbold" Width="10px" />
</asp:BoundField>
<asp:BoundField DataField="REJECTED_BY" HeaderText="Last Updated by">
<ItemStyle CssClass="labelbold" Width="10px" />
</asp:BoundField>
</Columns>
</asp:GridView>
And the code behind is:
protected void rptHotoIPDataInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = rptHotoIPDataInfo.Rows[rowIndex];
string name = row.Cells[9].Text;
var clickedButton = e.CommandSource as Button;
var clickedRow = clickedButton.NamingContainer as GridViewRow;
var clickedUserName = clickedRow.Cells[9].Text;
if (clickedUserName == "Approved")
{
clickedButton.Text = "Reject";
}
else if (clickedUserName == "REJECTED")
{
clickedButton.Text = "Approve"; // this statement is not updating the text
}
}
}

Hide edit button on Page_Load

I am trying to hide the Edit button when a student logs in and show it when the admin logs in. By default the edit button is visible. I want to hide the edit button on Page_Load. I have tried wrapping it in a div but it does not work for some reason. Any solutions??
GRIDVIEW CODE FOR .ASPX FILE:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" Width="1224px" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%#Eval("SrNo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Name" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Profile">
<ItemTemplate>
<asp:Label ID="lbl_Profile" runat="server" Text='<%#Eval("Profile") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Profile" runat="server" Text='<%#Eval("Profile") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CTC">
<ItemTemplate>
<asp:Label ID="lbl_CTC" runat="server" Text='<%#Eval("CTC") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_CTC" runat="server" Text='<%#Eval("CTC") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="InterOrFT">
<ItemTemplate>
<asp:Label ID="lbl_InternOrFT" runat="server" Text='<%#Eval("InternOrFT") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_InternOrFT" runat="server" Text='<%#Eval("InternOrFT") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lbl_Location" runat="server" Text='<%#Eval("Location") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Location" runat="server" Text='<%#Eval("Location") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
CODE FOR .ASPX.CS FILE:
protected void Page_Load(object sender, EventArgs e)
{
if(Session["user"] == null)
{
Response.Redirect("~/login.aspx");
}
else
{
if (Session["user"].ToString() != "admin")
{
addForm.Visible = false;
}
}
linkProfile.Text = Session["user"].ToString();
if (!IsPostBack)
{
GVBind();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cs);
con.Open();
SqlCommand cmd = new SqlCommand("insert into tblUpcoming values(#name, #profile, #ctc, #internFT, #location)", con);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#profile", txtProfile.Text);
cmd.Parameters.AddWithValue("#ctc", txtCTC.Text);
cmd.Parameters.AddWithValue("#internFT", txtInternFT.Text);
cmd.Parameters.AddWithValue("#location", txtLocation.Text);
cmd.ExecuteNonQuery();
con.Close();
GVBind();
clear();
}
void GVBind()
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("select compID as SrNo, name as Name, profile as Profile, internFT as InternOrFT, ctc as CTC, location as Location from tblUpcoming", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Read the session value directly at the aspx-file
<asp:Button ID="btn_Edit" runat="server" Text="Edit"
CommandName="Edit" Visible='<% Session["user"] == "admin" %>' />
also see ASP.NET "special" tags

Binding Shopping Cart Check box Session onto another Gridview

I am new to asp.net and I am trying to make a shopping cart. I have a shop set up that has a list of school supplies and a check box next to each one with a "Add to Cart" button on the bottom. I want to store only the checked items into a session and call it to another gridview on my Shopping Cart page. For some reason my gridview on my Shopping cart page is not appearing.
Shop.aspx
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Price" DataFormatString="{0:c2}" HeaderText="Price" SortExpression="Price" />
<asp:TemplateField HeaderText="Add To Cart">
<ItemTemplate>
<asp:CheckBox ID="cbAdd" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Table] ORDER BY [Id], [Name], [Price]"></asp:SqlDataSource>
</div>
<br />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:Button ID="btnAdd" runat="server" Text="Add To Cart" OnClick="btnAdd_Click" />
Shop.aspx.cs
protected void Page_Load(object sender, EventArgs e)//bind list to gridview
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();//create new datatable
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("ID"), new DataColumn("Name"), new DataColumn("Country") });
foreach (GridViewRow row in gvProducts.Rows)//for each row in the gridview
{
CheckBox ckRow = (CheckBox)row.FindControl("ckAdd");
if (ckRow !=null && ckRow.Checked)
{
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("Price");
Session["ShoppingCart"] = dt;//store datatable as session called ShoppingCart
}
Response.Redirect("~/ShoppingCart.aspx");
}
ShoppingCart.aspx
<h1>Shopping Cart</h1>
<asp:GridView ID="gvProductsList" runat="server" AutoGenerateColumns="true" ViewStateMode="Enabled">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Bind("Price")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:Textbox ID="txtQuantity" runat="server" Text='<%# Bind("Count")%>'></asp:Textbox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Total">
<ItemTemplate>
<asp:Label ID="lblProductTotal" runat="server" Text='<%# Convert.ToInt32(Eval("Quantity"))*Convert.ToInt32(Eval("Price"))%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Order Total: "></asp:Label>
</FooterTemplate>
</asp:TemplateField>
ShoppingCart.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = (DataTable)Session["ShoppingCart"];
gvProductsList.DataSource = dt;
gvProductsList.DataBind();
}
}
Try this:-
List<GridViewRow> gridcheckedrows = gvProducts.Rows.Cast<GridViewRow>().
Where(x => (x.FindControl("cbAdd") as CheckBox)
.Checked == true).ToList();
I used below custom data to bind the grid gvProducts
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Price");
DataRow dr = dt.NewRow();
dr[0] = "1";
dr[1] = "Sharique";
dr[2] = "120";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "2";
dr[1] = "Ansari";
dr[2] = "100";
dt.Rows.Add(dr);
gvProducts.DataSource = dt;
gvProducts.DataBind();
}
}
use this to bind you grid gvProductsList
List<GridViewRow> gridcheckedrows = gvProducts.Rows.Cast<GridViewRow>().Where(x => (x.FindControl("cbAdd") as CheckBox).Checked == true).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Price");
dt.Columns.Add("Count");
dt.Columns.Add("Quantity");
foreach (GridViewRow gvr in gridcheckedrows)
{
DataRow dr = dt.NewRow();
dr["Id"] = gvr.Cells[0].Text;
dr["Name"] = gvr.Cells[1].Text;
dr["Price"] = gvr.Cells[2].Text;
dr["Count"] = "1";
dr["Quantity"] = "2";
dt.Rows.Add(dr);
}
gvProductsList.DataSource = dt;
gvProductsList.DataBind();
and for grid gvProductsList use below html
<asp:GridView ID="gvProductsList" runat="server">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Bind("Price")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txtQuantity" runat="server" Text='<%# Bind("Count")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Total">
<ItemTemplate>
<asp:Label ID="lblProductTotal" runat="server" Text='<%# ((Convert.ToInt32(Eval("Quantity")))*(Convert.ToInt32(Eval("Price"))))%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Order Total: "></asp:Label>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Hope this will help you.

Delete and Update Row from GridView on Image Button

I want to delete the records from the Gridview on the click of ImageButton. Please see the GridView Code for your reference:-
<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="false" OnDataBound="grdCSRPageData_DataBound" PageSize="5" AllowPaging="true" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" OnRowCommand="grdCSRPageData_RowCommand">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField ItemStyle-Width="30">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
<asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
<asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" Width="15" Height="15" />
<span onclick="return confirm('Are you sure want to delete?')">
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="DeleteRow" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Tried with 'RowCommand' property of GridView and stucked how to delete the Row
See the code:-
protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;
int Id = Convert.ToInt32(e.CommandArgument);
//followed by your code
}
}
try this
protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;
grdCSRPageData.Rows.RemoveAt(rowIndex);
//delete from database
using (SqlConnection connection = new SqlConnection(connectionString))
{
int Id = Convert.ToInt32(e.CommandArgument);
string sql = "DELETE FROM YourTable WHERE ID = #ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.Parameters.AddWithValue("#ID",Id);
cmd.ExecuteNonQuery();
}
}
}
refer here for documentation about GridView remove.
SqlCommand documentation
update
to get the gridView from its row you can call this function
public static GridView GetParentGridView(GridViewRow row)
{
GridView gridView = (GridView)row.NamingContainer;
return gridView;
}
use it to get the gridview in my code
replace
grdCSRPageData.Rows.RemoveAt(rowIndex)
with
GetParentGridView((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).Rows.RemoveAt(rowIndex)
be sure also to bind the grid only if there is no postback on page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//bind the gridView
}
}
Tried with Something like this and it worked.:-
<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="True" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting" OnClientClick="return confirm('Are you sure you want to delete this record?')">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<%-- <asp:TemplateField ItemStyle-Width="30">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>--%>
<asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
<asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
<asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<%-- <asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit" Text="Edit" />--%>
<asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" Width="15" Height="15" />
<%-- <span onclick="return confirm('Are you sure want to delete?')"> -- %>
<%--<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" ></asp:LinkButton>--%>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Also see the code behind:-
protected void grdCSRPageData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
bool IsDeleted = false;
//getting key value, row id
int Id = Convert.ToInt32(grdCSRPageData.DataKeys[e.RowIndex].Value.ToString());
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "DELETE FROM tbl_Pages WHERE Id=#ID";
cmd.Parameters.AddWithValue("#ID", Id);
cmd.Connection = conn;
conn.Open();
IsDeleted = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
}
if (IsDeleted)
{
//record has been deleted successfully!
//call here gridview bind method and replace it..
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Page Succesfully deleted');window.location ='csrpage.aspx';", true); ;
grdCSRPageData.DataBind();
}
else
{
//Error while deleting record
Response.Write("Some error");
}
}
Also the binding of the data should be inside the '(!IsPostBack)' method

Trying to Add Insert Row to Footer in GridView ASP.net

I'm trying to give the user the ability to create a new record from the footer row and my event handler doesn't seem to be working... or maybe I'm going at this all wrong.
The insert button that I enabled in the gridview doesn't work either...checkout the site at http://aisched.engr.oregonstate.edu/admin/courses.aspx
Here is my code in front and behind:
public partial class admin_courses : System.Web.UI.Page
{
public Table table;
ListDictionary listValues = new ListDictionary();
TextBox textBox1 = new TextBox(); //Name
TextBox textBox2 = new TextBox(); //CR
TextBox textBox3 = new TextBox(); //CourseNum
TextBox textBox4 = new TextBox(); //Dept
protected void Page_Init()
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Footer) return; //Escape if not footer
textBox1.ID = "name";
textBox1.Width = 250;
textBox2.ID = "credit_hours";
textBox2.Width = 25;
textBox3.ID = "dept";
textBox3.Width = 30;
textBox4.ID = "class";
textBox4.Width = 25;
LinkButton add = new LinkButton();
add.ID = "add";
add.Text = "Add course";
add.CommandName = "add";
add.Click += new EventHandler(add_Click);
e.Row.Cells[1].Controls.Add(textBox1);
e.Row.Cells[2].Controls.Add(textBox2);
e.Row.Cells[3].Controls.Add(textBox3);
e.Row.Cells[4].Controls.Add(textBox4);
e.Row.Cells[5].Controls.Add(add);
}
public void add_Click(object sender, EventArgs e)
{
Response.Write("you Clicked Add Course!");
if (textBox1.Text != null && textBox2.Text != null && textBox3.Text != null && textBox4.Text != null) {
listValues.Add("name", textBox1.Text);
listValues.Add("credit_hours", textBox2.Text);
listValues.Add("dept", textBox4.Text); //For Visual
listValues.Add("class", textBox3.Text);
}
LinqDataSource1.Insert(listValues);
Response.Redirect("~/admin/courses.aspx");
}
}
<%# Page Language="C#" MasterPageFile="~/admin.master" AutoEventWireup="true" CodeFile="courses.aspx.cs" Inherits="admin_courses" Title="OSU Aisched | Admin - Courses" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="admin_nav_links" Runat="Server">
<ul id="main">
<li>Overview</li>
<li>Users</li>
<li class="current_page_item">Courses</li>
<li>Programs</li>
<li>Sections</li>
<li>Import</li>
<li>Logs</li>
</ul>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataClassesDataContext" EnableDelete="True"
EnableInsert="True" EnableUpdate="True" TableName="courses">
</asp:LinqDataSource>
<h1><a>Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="course_id" DataSourceID="LinqDataSource1"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2" AllowSorting="True" ShowFooter="True"
OnRowDataBound="GridView1_RowDataBound" >
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:BoundField DataField="course_id" HeaderText="ID"
ReadOnly="True" SortExpression="course_id" />
<asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
<asp:BoundField DataField="credit_hours" HeaderText="CR"
SortExpression="credit_hours" />
<asp:BoundField DataField="dept" HeaderText="Dept" SortExpression="dept" />
<asp:BoundField DataField="class" HeaderText="#" SortExpression="class" />
<asp:CommandField DeleteImageUrl="~/media/delete.png" ShowDeleteButton="True"
ShowEditButton="True" ShowInsertButton="True"/>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<br />
<asp:HyperLink ID="HyperLink1" runat="server" Target="~/admin/addCourse.aspx" Enabled="true"NavigateUrl="~/admin/addCourse.aspx" Text="Add New course"></asp:HyperLink>
<br />
</form>
</asp:Content>
I expect (or at least I certainly hope) there's a better way to do this, but try this:
<asp:LinqDataSource runat="server" ID="LinqDataSource1" ContextTypeName="Courses.DataClassesDataContext" TableName="Courses" EnableDelete="True" EnableUpdate="True" EnableInsert="True" />
<h1>
<a>
Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="course_id"
DataSourceID="LinqDataSource1" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"
BorderWidth="1px" CellPadding="3" CellSpacing="2" AllowSorting="True"
ShowFooter="True">
<Columns>
<asp:BoundField DataField="course_id" HeaderText="course_id" ReadOnly="True" SortExpression="course_id"
InsertVisible="False" />
<asp:TemplateField HeaderText="name" SortExpression="name" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NameTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="credit_hours" SortExpression="credit_hours">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="HoursTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dept" SortExpression="dept">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("dept") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("dept") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="DeptTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="class" SortExpression="class">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("class") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("class") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ClassTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="AddLinkButton" runat="server" CommandName="Add" Text="Add" CausesValidation="true" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
// We are in a Postback so check to see if the AddLinkButton was clicked
String eventTarget = Request.Form["__EVENTTARGET"].ToString();
if (eventTarget.EndsWith("addlinkbutton",StringComparison.InvariantCultureIgnoreCase))
{
// We are adding a new row so build a ListDictionary with the controls from the footer row
ListDictionary values = new ListDictionary();
values.Add("name", ((TextBox)GridView1.FooterRow.FindControl("NameTextBox")).Text);
values.Add("credit_hours", ((TextBox)GridView1.FooterRow.FindControl("HoursTextBox")).Text);
values.Add("dept", ((TextBox)GridView1.FooterRow.FindControl("DeptTextBox")).Text);
values.Add("class", ((TextBox)GridView1.FooterRow.FindControl("ClassTextBox")).Text);
// Pass the ListDictionary to the data source to send off to the database
LinqDataSource1.Insert(values);
// Refresh the grid so it shows the row we just added
GridView1.DataBind();
}
}
}
catch (Exception)
{
throw;
}
}
I couldn't make it work without writing code manually to do the Insert. Handling the AddLinkButton_Click event in the Page_Load event by examining the EventTarget hidden field to see if it ends with 'addlinkbutton' feels quite wrong, but it works.
A Sample pseudo code which can add from grid view footer, Initially data's are saved under View State, Using button click event to check the ViewState and insert the new data to the table.
aspx code
<asp:GridView ID="gvUser" runat="server" AutoGenerateColumns="false" ShowFooter="true" OnRowDataBound="gvUser_RowDataBound"
OnRowCommand="gvUser_RowCommand" OnRowDeleting="gvUser_RowDeleting" OnRowEditing="gvUser_RowEditing" CssClass="table table-bordered table-hover table-striped">
<EmptyDataTemplate>
No Data Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="User Details" HeaderStyle-Width="25%">
<ItemTemplate>
<asp:Label ID="lblCourse" runat="server" Text='<%# Eval("Details") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDetails" runat="server" DataTextField="Name" DataValueField="ID" CssClass="form-control" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="user Check One" HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckOne" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckOne").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckOne" runat="server" CssClass="i-checks" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HR Rec." HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckTwo" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckTwo").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckTwo" runat="server" CssClass="i-checks" />
</FooterTemplate>
<ItemStyle Wrap="true" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" CausesValidation="false" CommandName="Edit" ImageUrl="~/Contents/Images/pencil.svg" Width="20" Height="20"
ToolTip="Edit"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" CausesValidation="false" CommandName="Delete" ImageUrl="~/Contents/Images/remove.svg" Width="20" Height="20"
ToolTip="Delete"></asp:ImageButton>
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgBtnAdd" runat="server" CausesValidation="true" CommandName="Add" ImageUrl="~/Contents/Images/add.svg" Width="20" Height="20"
ToolTip="Add"></asp:ImageButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Server side code
protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
List<TableOne> controlDetails = new List<TableOne>();
controlDetails = dc.TableOne.Where(condition).ToList();
controlDetails.Insert(0, new TableOne() { ID = 0, Name = "Select Details" });
DropDownList ddlDetails = (e.Row.FindControl(ddlDetails) as DropDownList);
ddlDetails.DataSource = controlDetails;
ddlDetails.DataTextField = "Name";
ddlDetails.DataValueField = "ID";
ddlDetails.DataBind();
}
}
protected void gvUser_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
dr.Delete();
gvUser.Rows[RowIndex].Visible = false;
}
else if (e.CommandName == "Edit")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
ddlDetails.SelectedValue = dr["DetailID"].ToString();
CheckOne.Checked = Convert.ToBoolean(dr["CheckOne"]);
CheckTwo.Checked = Convert.ToBoolean(dr["CheckTwo"]);
dr.Delete();
}
else if (e.CommandName == "Add")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
if (ViewState["gvUser"] != null)
{
DataTable existingTable = (DataTable)ViewState["gvUser"];
existingTable.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = existingTable;
gvUser.DataSource = existingTable;
gvUser.DataBind();
}
else
{
DataTable dtUsers = new DataTable();
dtUsers.Columns.Add("ID");
dtUsers.Columns.Add("UserID");
dtUsers.Columns.Add("DetailsID");
dtUsers.Columns.Add("Details");
dtUsers.Columns.Add("CheckOne");
dtUsers.Columns.Add("CheckTwo");
dtUsers.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = dtUsers;
gvUser.DataSource = dtUsers;
gvUser.DataBind();
}
}
}
catch (Exception)
{
}
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (ViewState["gvUser"] != null)
{
TableOne userInfo = null;
List<TableOne> userDetails = new List<TableOne>();
DataTable userSpecificDetails = (DataTable)ViewState["gvUser"];
for (int i = 0; i < userSpecificDetails.Rows.Count; i++)
{
userInfo = new TableOne();
userInfo.UserID = UserID; //supply value
foreach (DataColumn col in userSpecificDetails.Columns)
{
switch (col.ColumnName)
{
case "DetailsID":
userInfo.DetailsID = Convert.ToInt16(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckOne":
userInfo.CheckOne = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckTwo":
userInfo.CheckTwo = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
}
}
userDetails.Add(userInfo);
}
if (userDetails.Count > 0)
{
dc.TableOne.InsertAllOnSubmit(userDetails);
dc.SubmitChanges();
}
}
}

Categories