I am using Nested GridViews where each row in the gridview has child gridView. I am using RowDataBound Event of Parent GridView, to Binding Child GridView. My Problem is that, how to get Child GridView's Button findcontrol value in Parent gridViews RowDataBound Event.
This is my Aspx page
<asp:GridView ID="grdSubClaimOuter" SkinID="GridView" runat="server" Width="100%"
AutoGenerateColumns="false" OnRowDataBound="grdSubClaimOuter_RowDataBound" OnRowCommand="grdSubClaimOuter_RowCommand"
ShowFooter="false" AllowPaging="true" OnPageIndexChanging="grdSubClaimOuter_PageIndexChanging">
<%--<AlternatingRowStyle BackColor="ButtonFace" />--%>
<Columns>
<asp:TemplateField ItemStyle-Width="5%">
<ItemTemplate>
<asp:HiddenField ID="hdnClaimNo" runat="server" Value='<%# Eval("ClaimNo") %>' />
<asp:Image runat="server" ID="img1" ImageUrl="../images/Collapse_plus.png" />
</ItemTemplate>
<ItemStyle Width="5%"></ItemStyle>
</asp:TemplateField>
<asp:GridView ID="grdSubClaim" runat="server" SkinID="GridView" CellPadding="4" Width="100%"
AutoGenerateColumns="false" ShowFooter="false" OnRowEditing="grdSubClaim_RowEditing"
OnRowCommand="grdSubClaim_RowCommand" OnRowDeleting="grdSubClaim_RowDeleted"
AllowPaging="false" >
<%--SkinID="GridView"--%>
<Columns>
<asp:TemplateField FooterStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left">
<HeaderTemplate>
Sub Claim No
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblSubClaimNoValue" Width="" runat="server" Text='<%#Eval("SubClaimNo")%>'></asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:Button ID="btnSubrogation" CssClass="groovybutton" runat="server" CommandName="Subrogation"
Text="Subrogation" CommandArgument='<%# Eval("ClaimNo") + "~" + Eval("SubClaimNo")%>' />
<asp:Button ID="btnSalvage" CssClass="groovybutton" runat="server" CommandName="Salvage"
Text="Salvage" CommandArgument='<%# Eval("ClaimNo") + "~" + Eval("SubClaimNo")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle CssClass="" />
<RowStyle CssClass="ob_gBody" />
<HeaderStyle CssClass="gridHeader" />
</asp:GridView>
<asp:Literal runat="server" ID="Literal2" Text="</td></tr>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is My aspx.cs file
protected void grdSubClaimOuter_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[1].Text.ToString() != " ")
{
Literal ltrChild = (Literal)e.Row.FindControl("ltrChild");
System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)e.Row.Cells[0].FindControl("img1");
ltrChild.Text = ltrChild.Text.Replace("trChildGrid", "trChildGrid" + e.Row.RowIndex.ToString());
string strChildGrid = "trChildGrid" + e.Row.RowIndex.ToString();
e.Row.Cells[0].Attributes.Add("OnClick", "OpenTable('" + strChildGrid + "','" + img.ClientID + "')");
e.Row.Cells[0].RowSpan = 1;
System.Web.UI.WebControls.GridView gvChild = (System.Web.UI.WebControls.GridView)e.Row.FindControl("grdSubClaim");
PolicyProcessor.DAL.Claim.ClaimSubClaim objDALClaimSubClaim = new PolicyProcessor.DAL.Claim.ClaimSubClaim();
PolicyProcessor.BOL.Claim.ClaimSubClaim objInfoClaimSubClaim = new PolicyProcessor.BOL.Claim.ClaimSubClaim();
HiddenField hdnClaimNo = (HiddenField)e.Row.FindControl("hdnClaimNo");
if (hdnClaimNo.Value != "")
{
objInfoClaimSubClaim.ClaimNo = hdnClaimNo.Value;
}
else
{
objInfoClaimSubClaim.ClaimNo = "0";
}
DataSet dsChild;
dsChild = objDALClaimSubClaim.ResultSet(objInfoClaimSubClaim, "SelectInnerGrid");
if (dsChild.Tables[0].Rows.Count > 0)
{
Button btn = (Button)gvChild.FindControl("btnSalvage");
//btn is null how to get text value in btn
btn.ForeColor = System.Drawing.Color.Red;
gvChild.DataSource = dsChild;
gvChild.DataBind();
}
else
{
Helper.EmptyGrid(gvChild, dsChild.Tables[0]);
}
}
}
}
if anyone knows it,please help me solve this problem.thanks in advance.
First get a reference to the child GridView, then use FindControl to get the Button inside it:
foreach (GridViewRow row in grdSubClaimOuter.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
GridView gvChild = (GridView) row.FindControl("grdSubClaim");
// Then do the same method for Button control column
if (gvChild != null)
{
foreach (GridViewRow row in gvChild .Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Button btn = (Button ) row.FindControl("buttonID");
if (btn != null )
{
// do your work
}
}
}
}
}
}
If you want value in parent grid's data bound event then use either way
1)You can also use your dsChild(Your dataset) and get field value which you are binding for button.
2) Get value of button from gvChild after binding child grid.
No need to loop into parent and child grid.
Related
Gridview Aspx Page
<asp:GridView ID="GridView2" runat="server" ShowFooter="true" GridLines="None" AutoGenerateColumns="False" CssClass="table table-hover">
<Columns>
<asp:TemplateField HeaderText="S.no">
<ItemTemplate><%#Container.DataItemIndex+1 %>
<asp:Label ID="lblReqNo1" Visible="false" runat="server" Text='<%#Eval("ReqNo")%>' ></asp:Label>
<asp:Label ID="lblFranchise_id" Visible="false" runat="server" Text='<%#Eval("franchise_id")%>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAccept" runat="server" CssClass="btn btn-danger"
Text="Accept Request" onclick="btnAccept_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Product Name" DataField="p_name" />
<asp:BoundField HeaderText="Quantity" DataField="Qty" />
<asp:BoundField HeaderText="Dealer Price" DataField="DP" />
<asp:BoundField HeaderText="Amount" DataField="amt" />
</Columns>
</asp:GridView>
C# Code
Button Click event which is in Gridview Footer Template
protected void btnAccept_Click(object sender, EventArgs e)
{
// GridViewRow row = (GridViewRow)((sender as Button).NamingContainer);
using (GridViewRow row = (GridViewRow)((Button)sender).NamingContainer)
{
Label lblReqNo = (Label)row.FindControl("lblReqNo1");
Label lblFranchise_id = (Label)row.FindControl("lblFranchise_id");
objFund.Transfer_id = int.Parse(lblReqNo.Text);
objFund.Type = 9;
int a = objFund.Insert();
objFund.Transfer_id = int.Parse(lblFranchise_id.Text);//franchise Id
objFund.CreditAmt = float.Parse(lblReqNo.Text);
objFund.Type = 5;
int b = objFund.Insert();
if (b > 0)
{
msg.Alert("Request accepted and mount Debited ");
}
}
}
it throws exception which is below
Object reference not set to an instance of an object.
Label lblReqNo = (Label)row.FindControl("lblReqNo1");//
by this line I'm getting only Null Values.How do i find Label Value?
Thanks
You can check row type wether it is header row or data row...
.. i.e. if it is data row then only your code will will execute
if (row.RowType == DataControlRowType.DataRow)
{
Label lblReqNo = (Label)row.FindControl("lblReqNo1");
Label lblFranchise_id = (Label)row.FindControl("lblFranchise_id");
objFund.Transfer_id = int.Parse(lblReqNo.Text);
objFund.Type = 9;
int a = objFund.Insert();
objFund.Transfer_id = int.Parse(lblFranchise_id.Text);//franchise Id
objFund.CreditAmt = float.Parse(lblReqNo.Text);
objFund.Type = 5;
int b = objFund.Insert();
if (b > 0)
{
msg.Alert("Request accepted and mount Debited ");
}
}
I'm having a problem calling a modal in asp
I need to set the postbackurl of linkbutton4 from code behind depending on what is selected in the dropdownlist! I have tried putting the postbackurl directlty on the linkbuttons tag it worked but when i change it from the code behind it doesnt BTW i change it when the link button is clicked.
Code behind for the linkbutton:
protected void LinkButton4_Click(object sender, EventArgs e)
{
var a = (Control)sender;
GridViewRow row = (GridViewRow)a.NamingContainer;
string b = row.Cells[0].Text;
Session["C"] = b;
DropDownList ddl =(DropDownList)row.Cells[7].FindControl("DropDownList1");
Session["D"] = ddl.SelectedItem.Text;
LinkButton lb = (LinkButton)row.Cells[7].FindControl("LinkButton4");
if (Session["D"].ToString() == "Upload")
{
lb.PostBackUrl = "preprod_design.aspx#edit";
// Upload();
}
if (Session["D"].ToString() == "Download")
{
Download();
}
infogridbind();
}
Here is the code for aspx :
<asp:GridView ID="GridView2" runat="server" ondatabound="GridView2_DataBound"
onrowdatabound="GridView2_RowDataBound"
onrowcreated="GridView2_RowCreated"
onselectedindexchanged="GridView2_SelectedIndexChanged"
onrowcommand="GridView2_RowCommand" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="SizeSetID" SortExpression="SizeSetID"/>
<asp:BoundField DataField="Revision No." SortExpression="RevisionNo" HeaderText = "Revision No."/>
<asp:TemplateField HeaderText ="Image">
<ItemTemplate>
<asp:Image ID="Image2" runat="server" onError = "this.style.display = 'none';" ImageUrl='<%#"~/ClientPoImage.ashx?autoId="+Eval("[SizeSetID]")%>' Width="50px" Height="40px"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Size Name" SortExpression="SizeName" HeaderText = "Size Name"/>
<asp:BoundField DataField="Quantity Requested" SortExpression="QuantityRequested" HeaderText ="Quantity Requested"/>
<asp:BoundField DataField="Quantity Received" SortExpression="QuantityReceived" HeaderText="Quantity Received"/>
<asp:BoundField DataField="Balance" SortExpression="Balance" HeaderText="Balance"/>
<asp:TemplateField HeaderText="Action">
<ItemTemplate >
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem>Upload</asp:ListItem>
<asp:ListItem>Download</asp:ListItem>
<asp:ListItem>Edit</asp:ListItem>
<asp:ListItem>Delete</asp:ListItem>
<asp:ListItem>Request</asp:ListItem>
<asp:ListItem>Receive</asp:ListItem>
</asp:DropDownList>
<asp:LinkButton ID="LinkButton4" runat="server" onclick="LinkButton4_Click">GO</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can change PostBackUrl for LinkButton inside DropDownList.SelectedIndexChanged event like this
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var ddl = (DropDownList)sender;
var row = (GridViewRow)(ddl.NamingContainer);
var lb = (LinkButton)row.FindControl("LinkButton4");
if (ddl.SelectedValue == "Upload")
{
lb.PostBackUrl = "preprod_design.aspx#edit";
}
if (ddl.SelectedValue == "Download")
{
....
}
}
also you need change markup like this
....
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" >
....
Remove AutoPostBack="True" From DropDownList, and in the header of page <%# Page Title="data"... EnableEventValidation="false" %>
After That You just go to click event of Link button and then
GridViewRow gr = (GridViewRow)(((LinkButton)sender).NamingContainer);
DropDownList ddl = (DropDownList)gr.FindControl("DropDownList1");
If(ddl.SelectedValue =="Upload") // or u can use ddl.SelectedItem.Text
{
//Upload();
}
else if(ddl.SelectedValue == "Download")
{
//Download();
}
I'm trying to set a my delete button visibility to true when the value of the last cell in row is equal to the session value which is the userID
Girdview UPDATED:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="attachID" HeaderText="Attachment ID" SortExpression="atID" HeaderStyle-CssClass="hidcol" ItemStyle-CssClass="hidcol"/>
<asp:BoundField DataField="attachmentTitle" HeaderText="Attachment Title" SortExpression="attachmentTitle" />
<asp:BoundField DataField="attachmentType" HeaderText="Attachment Type" SortExpression="attachmentType" />
<asp:BoundField DataField="attachmentDescription" HeaderText="Attachment Description" SortExpression="attachmentDescription" />
<asp:BoundField DataField="attachmentDate" HeaderText="Attachment Date" SortExpression="attachmentDate" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="download" CommandArgument='<%# Eval("attachmentFile") %>'><img src="CSS/images/download.png" alt="Download File" /></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="False" CommandArgument='<%# Eval("userID") %>' CommandName="Delete" ImageUrl="~/CSS/images/delete_page.png" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
I'm trying to set the Delete button property visibile if the userID machates the session["username"]
I'm not sure this is the right way or not.
Code-Behind UPDATED:
String searchValue = "" + Session["username"];
foreach (GridViewRow row in GridView1.Rows)
{
// Only look in data rows
if (row.RowType == DataControlRowType.DataRow ||
row.RowType == DataControlRowType.EmptyDataRow)
{
// Find the delete button by ID
ImageButton theDeleteButton = row.FindControl("ImageButton1") as ImageButton;
// Verify the button was found before we try to use it
if (theDeleteButton != null)
{
if (theDeleteButton.CommandArgument != searchValue)
{
// Make the button invisible
theDeleteButton.Visible = false;
}
}
}
}
How can i make it happen ?
thanks in advance!
The Code has been Updated
I recommend using a TemplateField for the delete button with a CommandName attribute (similar to what you are doing with the download link button) rather than a CommandField, because it will make your code for hiding the delete button cleaner, like this:
Markup:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="ButtonDelete" runat="server" CommandName="delete"
CommandArgument='<%# Eval("id") %>' Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
Code-behind:
foreach (GridViewRow row in GridView1.Rows)
{
// Only look in data rows
if (row.RowType == DataControlRowType.DataRow ||
row.RowType == DataControlRowType.EmptyDataRow)
{
// Find the delete button by ID
Button theDeleteButton = row.FindControl("ButtonDelete") as Button;
// Verify the button was found before we try to use it
if(theDeleteButton != null)
{
// Make the button invisible
theDeleteButton.Visible = false;
}
}
}
Note: The as operator will return null if the attempted cast cannot be completed successfully; hence the check for null against theDeleteButton variable.
I'm trying to populate multiple text boxes with data from a gridview when I click the link button (which is in fact the name of one of the fields in each row) but it isn't going through. I'm new to this - literally my first time. Any help would be most appreciated.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
AccountNumber.Text = selectedRow.Cells[1].Text;
Name.Text = selectedRow.Cells[1].Text;
Address1.Text = selectedRow.Cells[1].Text;
Address2.Text = selectedRow.Cells[2].Text;
Address3.Text = selectedRow.Cells[3].Text;
PhoneNumber.Text = selectedRow.Cells[4].Text;
FaxNumber.Text= selectedRow.Cells[5].Text;
CurrencyID.Text = selectedRow.Cells[6].Text;
}
}
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="Agent_Account_No"
DataSourceID="SqlDataSource1"
AlternatingRowStyle-BackColor ="Lavender"
HeaderStyle-BackColor="#9966FF"
AllowSorting="True" HeaderStyle-BorderColor="Black"
HorizontalAlign="Center"
RowStyle-BorderColor="Black"
EmptyDataText="There are no data records to display."
onrowcommand ="GridView1_RowCommand">
<AlternatingRowStyle BackColor="#CCFFCC" />
<Columns>
<asp:BoundField datafield="Agent_Account_No" HeaderText="Account No"
ItemStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle"
ItemStyle-Width="50"
SortExpression="Agent_Account_No"
ReadOnly="true">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"
Width="50px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Name" SortExpression="Agent_Name">
<ItemTemplate>
<asp:LinkButton ID="AgentName" runat="server"
Text='<%# Eval("Agent_Name") %>'
CommandName="Select"
CommandArgument='<%#Bind("Agent_Name") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
I got it to work this way - using help from this site:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
AccountNumber.Text = GridView1.DataKeys[row.RowIndex]["Agent_Account_No"].ToString();
......
}
I don't know if this declaration is right, but it works. However now that it works I see a problem that I didn't see before - see my profile and thanks a lot!
I would highly recommend using TemplateFields for all of your columns, like this:
Markup:
<Columns>
<asp:TemplateField HeaderText="Account No" SortExpression="Agent_Account_No">
<ItemTemplate>
<asp:Label ID="LabelAccountNumber" runat="server"
Text='<%# Eval("Agent_Account_No") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
...
<asp:TemplateField HeaderText="Name" SortExpression="Agent_Name">
<ItemTemplate>
<asp:LinkButton ID="AgentName" runat="server"
Text='<%# Eval("Agent_Name") %>'
CommandName="Select"
CommandArgument='<%#Bind("Agent_Name") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Now in the RowCommand method, you can use the FindControl() method of the grid view row to get to the text you are interested in, like this:
Code-behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
// Find the account number label to get the text value for the text box
Label theAccountNumberLabel = selectedRow.FindControl("LabelAccountNumber") as Label;
// Make sure we found the label before we try to use it
if(theAccountNumberLabel != null)
{
AccountNumber.Text = theAccountNumberLabel.Text;
}
// Follow the same pattern for the other labels to get other text values
}
}
I have two columns one for id & other for checkboxes.
i have taken checkboxes inside the gridview.
i wanted to see the checked values inside the gridview , If checkboxes are checked then i want those values i.e id
Asp.net
foreach(Gridviewrow gvr in Gridview1.Rows)
{
if(((CheckBox)gvr.findcontrol("CheckBox1")).Checked == true)
{
int uPrimaryid= gvr.cells["uPrimaryID"];
}
}
What you will have to do is use a template field:
<asp:TemplateField HeaderText="Field">
<ItemTemplate>
<div style="display: block">
<asp:Checkbox Checked='<%# DataBinder.Eval(Container.DataItem,"Field") %>'
runat="server" ID="chkField"></asp:Label>
</div>
</ItemTemplate>
</asp:TemplateField>
Then you can do:
foreach (DataGridRow dr in DataGrid1.Rows)
{
((CheckBox)gvr.FindControl("chkField")).Checked
}
to see if it's checked
in your aspx you have the following
<asp:GridView ID="gridViewID" runat="server" DataKeyNames="DataKey1,DataKey2,DataKey3" >
<Columns>
<asp:TemplateField HeaderText="selected">
<ItemTemplate>
<asp:CheckBox ID="checkBoxID" runat="server"
Checked='<%# Bind("Selected") %>'
OnCheckedChanged="checkBoxID_CheckedChanged"
AccessKey='<%# Container.DataItemIndex %>'
AutoPostBack="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in your event handler you do something similar to this:
protected void checkBoxID_CheckedChanged(object sender, EventArgs e)
{
var checkbox = (CheckBox)sender;
var rowIndex = Convert.ToInt32(checkbox.AccessKey);
var gridView = GetErhebungModulGridView();
var dataKey = gridView.DataKeys[rowIndex];
if (dataKey != null)
{
var dataKey1 = dataKey["DataKey1"];
var dataKey2 = dataKey["DataKey2"];
var dataKey3 = dataKey["DataKey3"];
//Do something with the variables keys above
}
}
<asp:gridview id="gv" runat="server">
<columns>
<asP:TemplateField>
<Asp:checkbox id="chk" runat="server" />
<Asp:literal id="ltlID" runat="server" visible="false" text='<%#eval("ID")%>' />
</asp:TemplateField>
</columns>
</asp:gridview>
For each row as gridviewrow in gv.rows
if ctype(row.findcontrol("chk"),checkbox).checked then
Dim _ID as integer = ctype(row.findcontrol("ltlID"),literal).text
end if
next