how to get values from gridview in asp.net web forms? - c#

hello all i am new to asp.net and i want to get values from grid view when i click on Edit or Delete or and i don't know how to do it i am sending data table to show table data and i don't want to use SQL Data Source from Visual tool box.
i have tried the following code but it gives error
protected void dgv1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int rowindex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
dgv1.EditIndex = rowindex;
dgv1.DataBind();
}
}
}
my view page code is as follows
<form id="form1" class="form-control form-group" runat="server">
<asp:Panel ID="pnlAddCustomers" runat="server" Height="376px">
<asp:Label ID="lblAddCustomers" runat="server" Text="Add Customers"></asp:Label>
<br runat="server"/>
<asp:Label ID="labelAddName" Text="Customer Name" runat="server"></asp:Label>
<asp:TextBox ID="txtboxcustomername" runat="server" Height="16px"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text=" Customer City "></asp:Label>
<asp:TextBox ID="txtboxcity" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text=" Customer Telephone "></asp:Label>
<asp:TextBox ID="txtboxtelephone" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Add Customers" Height="57px" Width="208px" OnClick="Button1_Click" />
</asp:Panel>
<asp:Panel ID="PnlViewCustomers" CssClass="table-dark" runat="server" Height="408px" >
<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
<asp:GridView ID="dgv1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" EnableTheming="True" PageSize="5" Width="100%" OnRowCommand="dgv1_RowCommand">
<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:Panel>
</form>
and body pic is as follow
enter image description here

Try this:
LinkButton lnkBtn = (LinkButton)e.CommandSource; // the button
GridViewRow gvRow = (GridViewRow)lnkBtn.Parent.Parent; // the row
You may also get the data key index by adding DataKeyNames="MyTableKeyID" to the <asp:GridView /> tab, then
string selectedKeyIndex = this.GridView1.DataKeys[myRow.RowIndex]["MyTableKeyID"].ToString();

Related

Update Panel Gridview not updating

When i click the submit button data is updated in db,but it is not listing
in gridview
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="True"><ContentTemplate>
<fieldset style="border: thin dotted #000000; height:919px;width:70%;background-color:#999999;"><legend style="font-size:15px;color:rgb(255,255,255);">Registration</legend><div> <asp:TextBox ID="txtcode" runat="server" CssClass="textbox" placeholder="Code"></asp:TextBox> </div> <br /><div><asp:TextBox ID="txtabr" runat="server" CssClass="textbox" placeholder="AER"></asp:TextBox> </div><br /> <div><asp:TextBox ID="txtauthor" runat="server" CssClass="textbox" placeholder="Author"></asp:TextBox></div><br /><div><asp:TextBox ID="txtEmail" runat="server" CssClass="textbox" placeholder="Email"></asp:TextBox</div><br /><div>
<asp:TextBox ID="txtpublishdate" runat="server" CssClass="textbox" placeholder="PublishDate"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server" BorderColor="#9900FF"
onclick="ImageButton1_Click" style="width: 14px"
/>
<asp:Calendar ID="Calendar1" runat="server" BackColor="White"
BorderColor="Black" DayNameFormat="Shortest" Font-Names="Times New Roman"
Font-Size="10pt" ForeColor="Black" Height="220px" NextPrevFormat="FullMonth"
TitleFormat="Month" Width="400px" onselectionchanged="Calendar1_SelectionChanged"
>
<DayHeaderStyle BackColor="#CCCCCC" Font-Bold="True" Font-Size="7pt"
ForeColor="#333333" Height="10pt" />
<DayStyle Width="14%" />
<NextPrevStyle Font-Size="8pt" ForeColor="White" />
<OtherMonthDayStyle ForeColor="#999999" />
<SelectedDayStyle BackColor="#CC3333" ForeColor="White" />
<SelectorStyle BackColor="#CCCCCC" Font-Bold="True" Font-Names="Verdana"
Font-Size="8pt" ForeColor="#333333" Width="1%" />
<TitleStyle BackColor="Black" Font-Bold="True" Font-Size="13pt"
ForeColor="White" Height="14pt" />
<TodayDayStyle BackColor="#CCCC99" />
</asp:Calendar></div><br /> <div>
<asp:TextBox ID="txtname" runat="server" CssClass="textbox" placeholder="BookName"></asp:TextBox> </div><br /><div>
<asp:TextBox ID="txtduedate" runat="server" CssClass="textbox" placeholder="DueDate"></asp:TextBox>
<asp:ImageButton ID="ImageButton2" runat="server" BorderColor="#9900FF" onclick="ImageButton2_Click"
/>
<asp:Calendar ID="Calendar2" runat="server" BackColor="White"
BorderColor="Black" DayNameFormat="Shortest" Font-Names="Times New Roman"
Font-Size="10pt" ForeColor="Black" Height="220px" NextPrevFormat="FullMonth"
TitleFormat="Month" Width="400px" onselectionchanged="Calendar2_SelectionChanged"
>
<DayHeaderStyle BackColor="#CCCCCC" Font-Bold="True" Font-Size="7pt"
ForeColor="#333333" Height="10pt" />
<DayStyle Width="14%" />
<NextPrevStyle Font-Size="8pt" ForeColor="White" />
<OtherMonthDayStyle ForeColor="#999999" />
<SelectedDayStyle BackColor="#CC3333" ForeColor="White" />
<SelectorStyle BackColor="#CCCCCC" Font-Bold="True" Font-Names="Verdana"
Font-Size="8pt" ForeColor="#333333" Width="1%" />
<TitleStyle BackColor="Black" Font-Bold="True" Font-Size="13pt"
ForeColor="White" Height="14pt" />
<TodayDayStyle BackColor="#CCCC99" />
</asp:Calendar>
</div><div> <asp:Label ID="Label5" runat="server" Text="IsActive" CssClass="label"></asp:Label> </div> <div><asp:CheckBox ID="chkactive" runat="server" /></div><div>
<asp:Label ID="Label6" runat="server" Text="Status" CssClass="label"></asp:Label> </div> <div><asp:CheckBox ID="chkstactive" Text="Active" runat="server" Checked="true" /> <asp:CheckBox ID="chknotactive" Text="NotActive" runat="server" /></div><br /><div><asp:Button ID="Btnsubmit" runat="server" Text="Submit" CssClass="bluebutton" onclick="Btnsubmit_Click" /> </div></fieldset></ContentTemplate></asp:UpdatePanel>
</div>
<div>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="True"><ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="#CC33FF" BorderColor="Black" ForeColor="White">
<AlternatingRowStyle BackColor="#666633" />
<Columns>
<asp:BoundField DataField="Code" HeaderText="Code" />
<asp:BoundField DataField="Author" HeaderText="Author" />
<asp:BoundField DataField="AER" HeaderText="ABR" />
</Columns>
<HeaderStyle BackColor="Black" />
<RowStyle BackColor="#666699" />
<SelectedRowStyle BackColor="#00FF99" />
</asp:GridView> </ContentTemplate><Triggers><asp:AsyncPostBackTrigger ControlID="Btnsubmit" EventName="Click" /></Triggers> </asp:UpdatePanel> </div> </form></body>
Data Successfully updated in table,after the insert gridview is not listing the latest record,if i refresh the page again the data will shown.please help ...........
protected void Btnsubmit_Click(object sender, EventArgs e)
{OleDbConnection conn = new OleDbConnection(); conn.ConnectionString =ConfigurationManager.ConnectionStrings["conn"].ToString();conn.Open();
string query = "insert into Register
(Code,Author,AER,PublishDate) values('" + txtcode.Text + "','" +
txtauthor.Text + "','" + txtabr.Text + "','" + txtpublishdate.Text + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.ExecuteNonQuery();
conn.Close();
BindGrid();
Clear();
}
protected void BindGrid()
{
Add code to your BindGrid() method to re-bind datagridview to a new data.
Something like this:
// Set up the data source.
bindingSource.DataSource = GetData("Select * From Register");
GridView1.DataSource = bindingSource;
In your BindGrid data add following code
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Register", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
Gridview1.DataSource = ds;
Gridview1.DataBind();
UpdatePanel1.Update();
}

Avoid page refresh when clicking on LinkButton in GridView

I have a GridView control, and inside of this control I have defined a link button using GridView.ItemTemplate.
I am using this to open a new window on click. When I click on the link button, however, the page refreshes before opening the new window.
How can I stop the page from refreshing after the link button is clicked?
HTML
<asp:UpdatePanel ID="UpdatePanel4" runat="server">
<ContentTemplate>
<asp:GridView ID="DataGrid1" style="visibility:visible" runat="server" AlternatingRowStyle-BackColor="#E9EDF5" Font-Names="Arial"
ForeColor="#09538A" Font-Size="12px" BackColor="#ffffff" BorderColor="DarkGray" Font-Bold="true"
HeaderStyle-BackColor="#298DC7" EnableViewState="false" CellSpacing="20"
CellPadding="10" HeaderStyle-Font-Bold="true" AutoGenerateColumns="False" OnRowCommand="DataGrid1__RowCommand" OnRowDataBound="DataGrid1__RowDataBound" >
<HeaderStyle Font-Names="Arial;" CssClass="MyHeaderStyle" Font-Size="13px" ForeColor="White" Font-Bold="True" Height="20" BackColor="#298DC7" ></HeaderStyle>
<asp:templatefield headertext="NDC" ItemStyle-CssClass="col" ItemStyle-HorizontalAlign="Justify" HeaderStyle-Width="10%" ItemStyle-Width="10%"> <Columns>
<itemtemplate>
<asp:linkbutton id="productcode" ForeColor="#09538A" runat="server" text='<%#Eval("product code")%>'></asp:linkbutton>
</itemtemplate>
</asp:templatefield>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<AjaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" BackgroundCssClass="modalBackground" CancelControlID="cancel" TargetControlID="Button3" runat="server" PopupControlID="pnlpopup"> </AjaxToolkit:ModalPopupExtender>
<asp:Button ID="Button3" runat="server" style="visibility:hidden" Text="Button" />
<asp:Panel ID="pnlpopup" CssClass="PanelPopup" runat="server">
<div style="width:inherit;text-align:center;">Products of <%=ndc %> Product Family</div>
<asp:GridView ID="GridView1" runat="server" AlternatingRowStyle-BackColor="#f1f4f8" Width="980px" Font-Names="Arial"
Font-Bold="True" ForeColor="#09538A" Font-Size="13px" BackColor="#ffffff" BorderColor="DarkGray"
HeaderStyle-BackColor="#99cccc" EnableViewState="false" CellSpacing="0" style="padding:10px;"
CellPadding="3" ShowFooter="false" AllowPaging="True" AutoGenerateColumns="False" OnRowDataBound="productInfo_RowDataBound" >
<HeaderStyle Height="10%" CssClass="MyHeaderStyle" Font-Size="13px" ForeColor="#FFFFFF" Font-Bold="true" BackColor="#298DC7"></HeaderStyle>
<rowstyle Height="20px" />
<alternatingrowstyle Height="20px"/>
<Columns>
<asp:boundfield datafield="product code" sortexpression="customers " ItemStyle-CssClass="col" headertext="NDC"/>
<div id="div<%# Convert.ToString(Eval("customer"))+ Convert.ToString(Eval("ManufacturingPartner"))+ Convert.ToString(Eval("product code"))+ Convert.ToString(Eval("Sales Person")) %>" style="display: none; position: relative; left: 15px; overflow: auto">
<asp:GridView ID="gvOrderInfo" runat="server" ForeColor="#09538A" AutoGenerateColumns="false" BorderStyle="Double" BorderColor="#df5015" Width="500px" OnRowDataBound="gvOrderInfo_RowDatabound">
<HeaderStyle CssClass="MyHeaderStyle" Font-Size="13px" ForeColor="#FFFFFF" Font-Bold="True" BackColor="#298DC7"></HeaderStyle>
<RowStyle BackColor="#E1E1E1" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:BoundField DataField="Order Number" HeaderText="Order Number" ItemStyle-Width="75px" ItemStyle-CssClass="col" HeaderStyle-HorizontalAlign="Left" />
</Columns>
</Columns>
</asp:GridView>
</div>
</asp:GridView>
</asp:Panel>
Codebehind
protected void DataGrid1__RowDataBound(Object sender, GridViewRowEventArgs e)
{
this.UpdatePanel4.Update();
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnk = e.Row.FindControl("ppp") as LinkButton;
lnk.Click += new EventHandler(link_Click);
//ScriptManager.GetCurrent(this).RegisterPostBackControl(lnk);
// string a = String.Format("0:N}",Convert.ToDecimal(e.Row.Cells[3].Text));
if (e.Row.Cells[0].Text != "Total")
{
//M1-Fmodification starts from here
if (ListBox2.Items.Count > 0)
//if (DataGrid1.Columns[0].Visible == true)
{
}
}
}
}
I would not use a LinkButton, but a straight html link.
<ContentTemplate>
<a href="#" ID='<%#Eval("product code")%>' onclick="doSomething();">
<%#Eval("productcode")%>
</a>
</ContentTemplate>
And then you can define some javascript in the page.
function doSomething(ProductCode) {
// enter the code here to open the window
}
Also, I would stay away from using UpdatePanel, but that's just my preference.

retain visible property of control through paging of nested gridview

I have a grid view within a grid view. When I click on edit of parent grid view the child grid view displays a checkbox. When I click on next page button of child grid view the controls that were made visible become invisible again. This is not the behaviour I require. I would like the controls that are made visible by clicking edit to remain visible through paging of the child grid view while parent grid view is in edit mode.
My markup:
<asp:GridView
ID="grdImages"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdImages_PageIndexChanging"
OnRowCancelingEdit="grdImages_RowCancelingEdit"
OnRowCommand="grdImages_RowCommand"
OnRowEditing="grdImages_RowEditing"
OnRowUpdating="grdImages_RowUpdating"
OnRowDeleting="grdImages_RowDeleting"
EmptyDataText="No Data Available at this Time"
OnRowDataBound="grdImages_RowDataBound"
DataKeyNames="productID" RowStyle-VerticalAlign="Top" RowStyle-HorizontalAlign="Center">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" HeaderText="Product ID" FooterText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" runat="server" Text='<%# Eval("ProductId") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdId" runat="server" AppendDataBoundItems="true" >
<asp:ListItem>Select a product</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Main Image" FooterText="Product Main Image" HeaderText="Product Main Image">
<ItemTemplate>
<asp:Label ID="lblMainImgId" runat="server" Text='<%# Eval("ImageId") %>' ></asp:Label>
<asp:Label ID="lblMainImgName" runat="server" Text='<%# Eval("ImageName") %>' ></asp:Label> <br />
<asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label runat="server" Font-Bold="true" Text="Current main image" ></asp:Label> <br />
<asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' /> <br />
<asp:Label runat="server" Font-Bold="true" Text="Upload a new image to replace the current main image." ></asp:Label> <br />
<asp:FileUpload ID="flupEditMain" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupMain" runat="server" AllowMultiple="false" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Supporting Images" FooterText="Supporting Images" HeaderText="Supporting Images">
<ItemTemplate>
<asp:Label ID="lblSupImages" runat="server" Visible="false" Font-Bold="true" Text="Select images to delete"></asp:Label><br />
<asp:GridView
ID="grdSupImages"
runat="server"
ShowHeader="false"
CellPadding="4"
ForeColor="#333333"
GridLines="None"
AutoGenerateColumns="False"
AllowPaging="true"
PageSize="4"
OnPageIndexChanging="grdSupImages_PageIndexChanging"
OnRowEditing="grdSupImages_RowEditing"
EnableViewState="true"
DataKeyNames="productID"
RowStyle-VerticalAlign="Top"
RowStyle-HorizontalAlign="Center"
EmptyDataText="No Supporting Images Found">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:Image ID="imgSup" runat="server" ToolTip='<%# Eval("ImgId") %>' AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:Label ID="imgSupName" runat="server" Text='<%# Eval("ImageName") %>' AssociatedControlID="imgSup"></asp:Label>
<asp:CheckBox ID="chkSupImages" runat="server" Visible="false" Text="Select Image" CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
<div style="clear:both;"> </div>
<asp:Label ID="lblFlupSupImages" runat="server" Font-Bold="true" Text="Add extra images" Visible="false" />
<br />
<asp:FileUpload ID="flupSupImages" runat="server" AllowMultiple="true" Visible="false" />
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupExtra" runat="server" AllowMultiple="true" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to delete these images?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
My code behind:
protected void grdImages_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grd = (GridView)e.Row.FindControl("grdSupImages"); // find controls
Label prodId = (Label)e.Row.FindControl("lblProdId");
grd.ToolTip = prodId.Text;
int product = Convert.ToInt32(prodId.Text); // assign values to variables.
BindNestedGrid(product, grd); // call the function.
}
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex == grdImages.EditIndex)
{
//Find Child GridView
GridView supImagesGrd = (GridView)e.Row.Cells[2].FindControl("grdSupImages");
if (supImagesGrd != null)
{
// find grid header label and make visible
Label gridHead = (Label)e.Row.Cells[2].FindControl("lblSupImages");
gridHead.Visible = true;
// find fileupload header label and make visible.
Label fileUpHead = (Label)e.Row.Cells[2].FindControl("lblFlupSupImages");
fileUpHead.Visible = true;
// find fileupload control and make it visible.
FileUpload flup = (FileUpload)e.Row.Cells[2].FindControl("flupSupImages");
flup.Visible = true;
//Loop through the GridView
foreach (GridViewRow row in supImagesGrd.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
//Find the CheckBox
CheckBox chb = (CheckBox)row.Cells[0].FindControl("chkSupImages");
if (chb != null)
{
chb.Visible = true;
}
}
}
}
}
}
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
BindNestedGrid(Convert.ToInt32(gv.ToolTip), gv);
}
If any more information or code is required please let me know.
For anyone who wants to know, I disabled paging of the child grid when edit button is clicked so all check boxes show on all rows of child grid now.

why on clicking on edit button of childgridview the childgridview hides?

This is what I have done for nested gridview :
The jQuery I have used to maintain this show hide is as:
<script type="text/javascript">
// Method for managing opening of gridview on + image and - image
$("[src*=plus]").live("click", function() {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "../Image/minus.gif");
});
$("[src*=minus]").live("click", function() {
$(this).attr("src", "../Image/plus.gif");
$(this).closest("tr").next().remove();
});
</script>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" DataKeyNames="num"
AutoGenerateColumns="False" Style="font-size: x-small" OnSelectedIndexChanging="GridView1_SelectedIndexChanging"
OnRowCancelingEdit="GridView1_RowCancelling" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand"
OnRowDeleting="GridView1_RowDeleting" ShowFooter="True"
OnRowEditing="GridView1_RowEditing" OnRowDataBound="GridView1_RowDataBound" OnSorting="GridView1_Sorting"
AllowSorting="true">
<RowStyle BackColor="#E3EAEB" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../Image/plus.gif" />
<asp:Panel ID="pnlOrders" style="display:none;">
<asp:GridView ID="GridView3" runat="server" CellPadding="4" ForeColor="#333333" DataKeyNames="sno"
OnRowCancelingEdit="GridView3_RowCancelling" OnRowUpdating="GridView3_RowUpdating"
OnRowEditing="GridView3_RowEditing" AutoGenerateColumns="False" Style="font-size: x-small">
<RowStyle BackColor="#E3EAEB" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField>
<HeaderTemplate>
Detailed Head
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="empdetails" Width="200px" runat="server" Text='<%# Eval("Details") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempdetail" Width="200px" runat="server" MaxLength="9" Text='<%# Eval("Details") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="sal" HeaderText="salary" />
<asp:CommandField ShowEditButton="true" EditText="Edit" />
</Columns>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="View" runat="server" Text="View" CommandName="view"
CommandArgument='<%#Container.DataItemIndex+1 %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Age</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblage" Width="80px" runat="server" MaxLength="4" Text='<%# Eval("age") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtage" runat="server" Text='<%# Eval("age") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
BloodGroup</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblBloodGroup" Width="100px" runat="server" MaxLength="9" Text='<%# Eval(" BloodGroup") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBloodGroup" runat="server" Text='<%# Eval(" BloodGroup") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" SelectText="Select" />
<asp:CommandField DeleteText="Reject" ShowDeleteButton="True" />
<asp:CommandField ShowEditButton="true" EditText="Edit" />
</Columns>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
On server side this is what I am doing:
protected void GridView3_RowEditing(object sender, GridViewEditEventArgs e)
{
DataSet ds = new DataSet();
tBL objBL = new tBL();
GridViewRow editedRow = GridView1.Rows[e.NewEditIndex];
//now search row for your control...
GridView GridView3 = (GridView)editedRow.FindControl("GridView3");
GridView3.EditIndex = e.NewEditIndex;
objtxtToTableBL.ViewBL(dt);
GridView3.DataSource = dt;
GridView3.DataBind();
}
protected void GridView3_RowCancelling(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
}
protected void GridView3_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
I am binding the nested gridview on rowdatabound of GridView1 and that works fine.
The problem with all this is when I click on the edit button of innergridview(child) it get hide as the page postback .
What should I do so that when I click on its edit button the child gridview remains open and it gets hides only when I click on minus button. Please help it has already taken 3 days of mine.

Import csv file into existing gridview

I have a tabcontainer with two tabs:
The first tab contains a button.
The second tab contains a gridview that has three textboxes.
I would like to do the following: when one clicks on the button in tab1, the gridview in tab2 is populated with data in a prespecified csv file (note that the file has the same column names as the gridview).
This is what I have so far, but for some reason, the gridview doesn't get populated with the data in the csv.
aspx.cs
<asp:UpdatePanel ID="WholeUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0" HeaderText=""
Width="900px" TabStripPlacement="Top" ScrollBars="None" UseVerticalStripPlacement="false"
VerticalStripWidth="120px" BackColor="White" BorderColor="White"
Style="margin-right: 84px">
<asp:TabPanel ID="OptionPanel" runat="server" Height="600px">
<HeaderTemplate>
Simulation Option
</HeaderTemplate>
<ContentTemplate>
<asp:Button ID="PreviousSimButton" runat="server" Text="Run Previous Simulation" Width="250px" OnClick="PreviousSimButton_OnClick" />
<ContentTemplate>
</asp:TabPanel>
<asp:TabPanel ID="TabPanel1" runat="server" Height="600px" >
<HeaderTemplate>
General
</HeaderTemplate>
<ContentTemplate>
<asp:UpdatePanel ID="TestUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="GeneralPanel" runat="server" Height="274px">
<div style="overflow: auto; height: 222px; width: 100%">
<asp:GridView ID="InflationGridView" runat="server" AutoGenerateColumns="False" Width="52%"
ShowHeaderWhenEmpty="True" CellPadding="4" ForeColor="#333333" GridLines="None"
AllowSorting="True" ShowFooter="True">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" Height="2px" />
<Columns>
<asp:TemplateField HeaderText="Start Year">
<ItemStyle Font-Size="13px" Width="20%" HorizontalAlign="Center" />
<ItemTemplate>
<asp:TextBox ID="StartInflationTextBox" runat="server" Width="60px" Text="" Style="text-align: center;"></asp:TextBox>
<asp:NumericUpDownExtender ID="StartInflationNumericUpDownExtender" runat="server"
TargetControlID="StartInflationTextBox" Minimum="1" Width="60">
</asp:NumericUpDownExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Year">
<ItemStyle Font-Size="13px" Width="20%" HorizontalAlign="Center" />
<ItemTemplate>
<asp:TextBox ID="EndInflationTextBox" runat="server" Width="60px" Text="" Style="text-align: center;"></asp:TextBox>
<asp:NumericUpDownExtender ID="EndInflationNumericUpDownExtender" runat="server"
TargetControlID="EndInflationTextBox" Minimum="1" Width="60">
</asp:NumericUpDownExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Inflation Rate">
<ItemStyle Font-Size="13px" Width="25%" HorizontalAlign="Center" Height="2px" />
<ItemTemplate>
<asp:TextBox ID="InflationTextBox" runat="server" Text="" Width="60px" Style="text-align: center;"></asp:TextBox>
%
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="AddNewInflationRowButton" runat="server" Text="Add New Row" OnClick="AddNewInflationRowButton_Click"
Height="25px" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle Font-Bold="True" ForeColor="White" Height="20px" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" Height="10px" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</contenttemplate>
</asp:TabPanel>
</asp:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
aspx.cs
protected void PreviousSimButton_OnClick(object sender, EventArgs e)
{
TabContainer1.ActiveTabIndex = 1;
string file = "C:\\inst_research\\MonteCarlo\\Data\\inflation.csv";
InflationGridView.DataSource = (DataTable)ReadToEnd(file);
InflationGridView.DataBind();
WholeUpdatePanel.Update();
TestUpdatePanel.Update();
}
private object ReadToEnd(string filePath)
{
DataTable dtDataSource = new DataTable();
string[] fileContent = File.ReadAllLines(filePath);
if (fileContent.Count() > 0)
{
string[] columns = fileContent[0].Split(',');
for (int i = 0; i < columns.Count(); i++)
{
dtDataSource.Columns.Add(columns[i]);
}
for (int i = 1; i < fileContent.Count(); i++)
{
string[] rowData = fileContent[i].Split(',');
dtDataSource.Rows.Add(rowData);
}
}
return dtDataSource;
}
Your code should not give any issues if you use :
fileContent.Length instead of fileContent.Count()

Categories

Resources