Row command with Link button in GridView - c#

I have two GridViews. GridView1 contains 2 link buttons in a column. When I select a link button in GridView1, the details of the link button should be displayed in GridView2.
GridView2 contains a column with radio buttons. I need to fill the radio buttons dynamically from the database.
How can I fill the Radio button list of GridView2 by using GridView1_RowCommand? Or Can I get it from the RowDataBound event of GridView2?
code behind:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Yes")
{
GridViewRow gvRow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int RowIndex = gvRow.RowIndex;
Int32 iAppID = Convert.ToInt32(GridView1.DataKeys[gvRow.RowIndex].Value.ToString());
dset = userApps.UserSelectedApp(iUserID, iAppID);
if (dset.Tables[0].Rows.Count > 0)
{
GridViewRow gRow = GridView2.Rows[RowIndex];//I need to create object to this Gridview2, and fill the radiobutton list with some values
RadioButtonList rdbtnSubPlans = (RadioButtonList)e.gRow.Cells[2].FindControl("rdbSubPlans");
ds = userApps.UpgradePlans(iUserID, iAppID);
if (ds != null)
{
rdbtnSubPlans.DataSource = ds;
rdbtnSubPlans.DataValueField = "PlanID";
rdbtnSubPlans.DataTextField = "Plans";
rdbtnSubPlans.DataBind();
}
}
}
if (e.CommandName == "No")
{}
dtset = user.UserSelectedAppication(iUserID, iAppID);
GridView2.DataSource = dtset;
GridView2.DataBind();
MultiView1.SetActiveView(viewRenewOrUpdate);
}
}
ASPX code for the GridViews
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ApplicationID"
OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand"
OnSorting="GridView1_Sorting" OnDataBound="GridView1_DataBound"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="S.No" ItemStyle-HorizontalAlign="center" HeaderStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:Label ID="l1" runat="server" Text="1"></asp:Label>
</ItemTemplate>
<HeaderStyle Width="10%" />
</asp:TemplateField>
< Some Bound Fields>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkYes" runat="server" Text="Yes"
CssClass="lnkbtn" Visible="false" commandname="Yes" Width="100px" >
</asp:LinkButton>
<asp:LinkButton ID="lnkNo" runat="server" CssClass="lnkbtn" Text="No"
Visible="false" commandname="No" ToolTip="No and Yes current plan" Width="100px" >
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="GridView2" runat="server" DataKeyNames="ApplicationID"
OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:BoundField DataField="ApplicationName" HeaderText="Application name">
<HeaderStyle Width="30%" />
<ItemStyle CssClass="col" />
</asp:BoundField>
<asp:TemplateField HeaderText="Plans">
<ItemTemplate>
<asp:RadioButtonList ID="rdbSubPlans" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="rdbSubPlan_OnSelectedIndexChanged" Enabled="false">
</asp:RadioButtonList>
</ItemTemplate>
<ItemStyle CssClass="col" />
</Columns>
</asp:GridView>

Fill Gridview2 first, and then do the following corrections:
GridViewRow gRow = GridView2.Rows[0]
RadioButtonList rdbtnPlans = (RadioButtonList)gRow.FindControl("rdbPlans");

Related

Getting value from textbox in gridview

I have a GridView on which I am binding 2 textbox and a update button. grid view is dynamic so Row numbers can vary depending upon the size of dataset. Now what I want is when I change values in this textbox and click on update then data for that row in database should get updated. The textbox values in database should get updated.
This is my code:
<asp:GridView ID="dgAbstractSummary" runat="server" AutoGenerateColumns="False" OnRowDataBound="dgAbstractSummary_RowDataBound" OnRowCreated="dgAbstractSummary_RowCreated"
Visible="true">
<Columns>
<asp:BoundField HeaderText="ID" DataField="id" HtmlEncode="false"></asp:BoundField>
<asp:BoundField HeaderText="Abstract Title" DataField="title" HtmlEncode="false"></asp:BoundField>
<asp:TemplateField HeaderText="Significance Score">
<ItemTemplate>
<asp:TextBox ID="txtSignificanceScore" AutoPostBack="true" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"significanceScore")%>'></asp:TextBox>
<div class="voffset3"></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Innovation Score">
<ItemTemplate>
<asp:TextBox ID="txtInnovationScore" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"innovationScore")%>'></asp:TextBox>
<div class="voffset3"></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button AutoPostBack="true" CssClass="btn btn-primary btn-embossed" ID="btnUpdate" runat="server"
Text="Update"
OnClick="btnUpdate_Click" CommandArgument='<%#Eval("Id") %>' />
<div class="voffset3"></div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="panel-default"></HeaderStyle>
<RowStyle CssClass=""></RowStyle>
</asp:GridView>
C#
dgAbstractSummary.DataSource = dsResult; // dataset contains values which I am binding to grid columns
dgAbstractSummary.DataBind();
protected void btnUpdate_Click(object sender, EventArgs e)
{
Button myUpdateButton = (Button)sender;
}
Here Id (first column) is the unique key for each row.
Use find control function to find the two text boxes on the grid view row using your buttons sender event.
Something like this.
Button btn = (Button)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
TextBox details = gvr.FindControl("detailsText") as TextBox;
//do something with details
TextBox cusID = gvr.FindControl("TextBox2") as TextBox;

How can i hold gridview row selected values into a string in asp.net

I have gridview control it contains 6 columns when i click 6th column row of gridview i need to selecte that contains columns row text into a string. how can i take here i am taking commandargument is a string and how can i take another column names text
my code:
<asp:GridView ID="GridView1" Width="950px" CssClass="Grid" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:GridView ID="GridView1" Width="950px" CssClass="Grid" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="" ItemStyle-ForeColor="White" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="SName" HeaderText="SName" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="Size" HeaderText="Size(MB)" />
<asp:BoundField DataField="Time" HeaderText="Time" />
<asp:TemplateField HeaderText="FileName">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" CausesValidation="False" CommandArgument='<%# Eval("FileName") %>'
CommandName="Download" Text='<%# Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S.No." Visible="false">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string ID1;
if (e.CommandName == "Download")
{
GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int rowIndex = gvr.RowIndex;
Label Itemid = (Label)GridView1.Rows[rowIndex].FindControl("lblID");
ID1 = (Itemid).Text;
Session["ID"] = ID1;
string filename = e.CommandArgument.ToString();
//here how can i hold another column text
}
}
I have a easiest way to do this same thing...
<asp:Label ID="lblName" runat="server" Text='<%#Eval("ID").ToString() +", "+ Eval("OtherCoulmn").ToString() %>'></asp:Label>
--- hope it helps
Also the best way is to do something like this
((MyObject)Container.DataItem).MyProperty where MyObject is the Model which you bind with grid and property which you wan to use in rowcommand its clean .
Simply follow the bellow code sample:
protected void btnEdit_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
Label lblId = gvCipamMember.Rows[gvr.RowIndex].FindControl("lblPersonId") as Label;
cmd = new SqlCommand("SELECT Id,Res_Person,Email_ID,Mobile_NO,Cipam_Flag FROM Responsibilty_Master WHERE Id=#Id", con.MyConnection);
cmd.Parameters.AddWithValue("#Id", Convert.ToInt32(lblId.Text.ToString()));
dt = new DataTable();
con.MyConnection.Open();
dt.Load(cmd.ExecuteReader());
if (dt.Rows.Count > 0)
{
txtPersonName.Text = dt.Rows[0]["Res_Person"].ToString();
txtEmail.Text = dt.Rows[0]["Email_ID"].ToString();
txtMobileNo.Text = dt.Rows[0]["Mobile_NO"].ToString();
if(Convert.ToBoolean(dt.Rows[0]["Cipam_Flag"].ToString())==true)
{
chkbCipamFlag.Checked = true;
}
}
}

finding label in itemTemplate and bind data from code behind

I wanted to display value in a label (label inside itemTemplate)
i have tried this approach
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
if (string.IsNullOrEmpty(s) == false)
{
foreach (GridViewRow row in GridView1.Rows)
{
string LabelText = ((Label)row.FindControl("labelSelf")).Text;
LabelText = s;
Response.Write(LabelText+"test");
}
}
but nothing is shown in the label inside the gridview. IT should display the value of s.
Next approach was
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
Label labelSelfCollect = GridView1.FindControl("labelSelf") as Label;
labelSelfCollect.Text = "Self Collect at "+ s;
I got this error
System.NullReferenceException: Object reference not set to an instance of an object.
and the last approach that i have used is
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
if (string.IsNullOrEmpty(s) == false)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label labelcollect = row.FindControl("labelSelf") as Label;
labelcollect.Text = "self collect at "+ s;
}
}
}
using this method also it shows nothing.How should i assign the s value into this labelSelf(label inside itemTemplate)?
my aspx code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="772px" style="margin-left: 120px; text-align: left" Height="100px" DataKeyNames ="progressID" OnRowDataBound="GridView1_OnRowDataBound" OnRowDeleting="GridView1_RowDeleting" CellPadding="4" CssClass="rounded_corners" HeaderStyle-Height="40px">
<AlternatingRowStyle CssClass="rounded_corners tr tr" />
<Columns>
<asp:BoundField ControlStyle-BorderWidth="60" DataField="dateupdate" HeaderText="Date Update" DataFormatString="{0:dd/MM/yyyy}" >
<ControlStyle BorderWidth="60px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Progress">
<ItemTemplate >
<%# Eval("message") %>
<br />
<asp:label ID="labelRemark" runat="server" style="Font-Size:11.5px;" text='<%# Eval("remark") %>'></asp:label><br />
<asp:Label ID="labelSelf" runat="server" style="Font-Size:11.5px;" ></asp:Label><br />
<div id="div<%# Eval("progressID") %>" >
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
DataKeyNames="progressID" style="text-align:center; font-size:small;" CellPadding="4" OnRowCommand="GridView2_RowCommand" GridLines="None" CssClass="rounded_corners" Width="500px" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="tackingNo" HeaderText="Courier Tracking No" ItemStyle-Font-Size="Small" ItemStyle-Width="150px" >
</asp:BoundField>
<asp:BoundField DataField="courierDate" HeaderText="Courier Date">
</asp:BoundField>
<asp:TemplateField HeaderText="Provider">
<ItemTemplate>
<asp:HyperLink Text='<%#Eval("providernm")%>' Target="_blank" runat="server" DataNavigateUrlFields="companyurl" NavigateUrl='<%#Eval("companyurl")%>' ></asp:HyperLink>
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tracking" >
<ItemTemplate>
<br />
<asp:HyperLink Text="Track Here" Target="_blank" runat="server" DataNavigateUrlFields="trackingurl" NavigateUrl='<%#Eval("trackingurl")%>' ></asp:HyperLink>
<br />
<asp:Label ID="Label4" runat="server" Text="* check after 24 hours" Font-Italic="true"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="LinkButtonDELETE" runat="server" CommandName="Delete" Text="Delete" OnClientClick= "return confirm('Confirm Delete progress?')"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Thank you.
Use GridView1_OnRowDataBound instead of foreach (GridViewRow row in GridView1.Rows). Apart from that your first approach is correct. You're simply not assigning the Text property there but reading from it.
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Label labelSelf = (Label)e.Row.FindControl("labelSelf");
labelSelf.Text = address.getSelfCollectAddress(orderNoTracking); // maybe you need to retrieve the orderNoTracking from another control in this row or from it's datasource
}
}

How to populate multiple textboxes from a row in gridview that uses a link button

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
}
}

How to get the link button id which is in gridview1 on button1click which is in gridview2 - asp.net

i have placed two gridview controls,in which i have buttons. i have linkbutton in gridview1 and button1 in gridview2.
i need to get the linkbutton id on button1 click in grdiview2.
here is the snippet of my code:
<asp:GridView ID="gvdatasubcategory" runat="server" AllowPaging="false" AllowSorting="false"
CssClass="gvdatarow" ShowHeader="false" AutoGenerateColumns="False" OnRowCommand="gvdatasubcategory_RowCommand">
<Columns>
<asp:TemplateField ItemStyle-Font-Names="Estrangelo Edessa" HeaderStyle-Font-Names="Estrangelo Edessa">
<ItemTemplate>
<div class="subcategory_type">
<div id="abd" runat="server">
<asp:LinkButton ID="lnkGridSubCategory" runat="server" CssClass='<%# "CategoryTab" + Eval("id") %>'
Width="80px" Height="26px" Text='<%#DataBinder.Eval(Container.DataItem, "SubCategory")%>'
CommandName="Test"></asp:LinkButton>
</div>
</div>
here is gridview 2:
<asp:GridView ID="Categorygvdata" runat="server" AllowPaging="false" AllowSorting="false"
CssClass="gvdatarow" ShowHeader="false" DataKeyNames="Id" AutoGenerateColumns="False"
OnSelectedIndexChanged="Categorygvdata_SelectedIndexChanged">
<HeaderStyle BackColor="#013a04" Height="25px" ForeColor="White" />
<Columns>
<asp:TemplateField ItemStyle-Font-Names="Estrangelo Edessa" HeaderStyle-Font-Names="Estrangelo Edessa">
<ItemTemplate>
<div class="category_type">
<asp:Button ID="Button1" runat="server" CommandName="FilterCategory" CommandArgument='<%# Eval("Id") %>'
CssClass='<%# "CategoryTab" + Eval("Id") %>' Text='<%# Eval("Category") %>' OnCommand="Button1_Click" />
</div>
</ItemTemplate>
<HeaderStyle Font-Names="Estrangelo Edessa" Width="5px" />
<ItemStyle Font-Names="Estrangelo Edessa" Width="5px" Wrap="false" HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
server side code:
i have tried this but no luck.!
protected void Button1_Click(object sender, CommandEventArgs e)
{
LinkButton GridView1 = (LinkButton)gvdatasubcategory.FindControl("Categorygvdata");
foreach (GridViewRow row in gvdatasubcategory.Rows)
{
LinkButton btn = (LinkButton)row.FindControl("lnkGridSubCategory");
string strClientID = string.Empty;
strClientID = btn.ClientID;
}
}
Need help.
Thankyou.
Try this
LinkButton lnkGridSubCategory = (LinkButton)gvdatasubcategory.FindControl("lnkGridSubCategory");
foreach (GridViewRow row in gvdatasubcategory.Rows)
{
string strClientID = string.Empty;
strClientID = lnkGridSubCategory.ClientID;
}
The reason why your code is failing is that you are casting a grid view to a link button which will not work.

Categories