Get selected Index in gridview by clicking on button - c#

I have grid view and there is a template field in it and i want to get the selected row's index by clicking on button i cant change the field type cause i want to change the visibale attribute in my behind code manually.
Here is my code:
<asp:GridView ID="gvService" runat="server" BackColor="White" AutoGenerateColumns="False"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" DataKeyNames="Service_Id, UserId">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" HeaderStyle-BackColor="Gray">
<HeaderStyle BackColor="Gray"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="L_Name" HeaderText="LastName" SortExpression="L_Name"
HeaderStyle-BackColor="Gray">
<HeaderStyle BackColor="Gray"></HeaderStyle>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="bttCost" runat="server" Text="Cost" OnCommand="Cmd_Pay" Visible='<%# IsNotPaid((Decimal)Eval("Cost")) %>' />
</ItemTemplate>
</asp:TemplateField>
and my behind code:
int rowIndex = gvService.SelectedIndex;
HFServiceID.Value = (string)gvService.DataKeys[rowIndex]["Service_Id"];
HFUserID.Value = (string)gvService.DataKeys[rowIndex]["UserId"];

To get the row index the button that was clicked belongs to, add this in your onclick event.
var rowIndex = ((GridViewRow)((Control)sender).NamingContainer).RowIndex;

Related

Get Gridview Datakey from nested gridview

I've got a gridview nested inside another gridview. What I need is that on the inner gridview get the DataKey from the outer gridview.
How can I pass it?
Thanks.
UPDATE
<asp:GridView ID="gvPeople" runat="server" AutoGenerateColumns="false" CssClass="Grid" DataKeyNames="person_id" OnRowDataBound="gvPeople_RowDataBound">
<Columns>
<asp:TemplateField HeaderStyle-Width="10px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="images/glyphicons/png/glyphicons_236_zoom_in.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvDocuments" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid" DataKeyNames="document_id" ShowFooter="true"
OnRowCommand="gvDocuments_RowCommand" OnRowDataBound="gvDocuments_RowDataBound" OnRowDeleted="gvDocuments_RowDeleted" OnRowDeleting="gvDocuments_RowDeleting"
GridLines="Horizontal" >
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="document_date" HeaderText="Document Date" />
<asp:BoundField ItemStyle-Width="100px" DataField="value" HeaderText="Value" DataFormatString="{0:#,##.00 €}" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button runat="server" ID="delbutton" CommandArgument='<%# Eval("document_id") %>' CommandName="Delete" Text="Delete" />
<asp:Button runat="server" ID="editbutton" CommandArgument='<%# Eval("document_id") %>' Text="Edit" UseSubmitBehavior="false" />
</ItemTemplate>
<FooterTemplate>
<asp:Button runat="server" ID="newdoc" CommandName="New" Text="New Document" UseSubmitBehavior="false" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="ndocs" HeaderText="Nº of Documents" />
<asp:BoundField ItemStyle-Width="150px" DataField="total_cost" HeaderText="Total Cost" DataFormatString="{0:#,#0.00 €}" />
</Columns>
</asp:GridView>
Here is my aspx code, which is all working, with the excpetion of the new document button, which runs a javascript button, as the edit button, but on this one I need to pass the person_id, from the row of the gvPeople, so when I create a new gvDocuments row, it will make it to that person id.
Thanks.
Just put it to work.
Add a hiddenfield before the child gridview with the value that I want.
On the RowDataBound of the child gridview, added this:
string str= ((HiddenField)e.Row.Parent.Parent.Parent.FindControl("hf")).Value.ToString();
And now use the str value for anything that I want.
You need to first access each of the parent gridview row then access the child gridview row then access the datakey.
Example:
foreach (GridViewRow rowPeople in gvPeople.Rows)
{
GridView gvDocuments = (GridView)rowPeople.FindControl("gvDocuments");
//this will get you the outer/parent gridview datakeys
gvDocuments.DataKeys[rowPeople.RowIndex].Values[0].ToString();
foreach (GridViewRow rowDocuments in gvDocuments.Rows)
{
//this will get you the inner/child gridview datakeys
gvDocuments.DataKeys[rowDocuments.RowIndex].Values[0].ToString();
}
}
Let me know if that works for you!

ASP.Net gridview editing - finding a control on a multipage grid view

I have a gridview that has a textbox in one of cells in my aspx file.
After clicking the edit link in the row, I am able to get the control programatically in the rowdatabound event with this:
e.Row.FindControl("controlPlaceholder");
Using the edit index from the edit event works as well.
However, the control is only enabled on the first page of the gridview. On any other page, FindControl() returns null.
What could be the reason for this? Are there any potential solutions to this issue? I've looked for a solution but haven't had any luck with finding someone who has this particular problem.
Markup:
<asp:Panel ID="pnlAccountAssignment" runat="server" CssClass="clsDataPanel" meta:resourcekey="pnlAccountAssignmentResource1">
<asp:GridView ID="gvAccountAssignment" runat="server" AutoGenerateColumns="False"
AllowPaging="true" PageSize="25" OnRowDataBound="gvAccountAssignment_RowDataBound"
OnRowCancelingEdit="gvAccountAssignment_RowCancelingEdit" OnRowEditing="gvAccountAssignment_RowEditing"
OnRowUpdating="gvAccountAssignment_RowUpdating" OnPageIndexChanging="gvAccountAssignment_PageIndexChanging"
OnSorting="gvAccountAssignment_Sorting" AllowSorting="True" meta:resourcekey="gvAccountAssignmentResource1">
<RowStyle BackColor="White" ForeColor="Black" />
<HeaderStyle CssClass="clsGrayBkgCell" HorizontalAlign="Center" VerticalAlign="Bottom" />
<Columns>
...Other Columns...
<asp:TemplateField meta:resourcekey="TemplateFieldResource8">
<ItemStyle CssClass="clsNumber" HorizontalAlign="Left" VerticalAlign="Top" />
<EditItemTemplate>
<asp:TextBox ID="column13PlaceHolder" runat="server" CssClass="clsNormalLabel">
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblprevMonth" runat="server" CssClass="clsNormalLabel"></asp:Label>
</ItemTemplate>
<HeaderTemplate>
<asp:LinkButton runat="server" ID="hypSortGLBal" OnClick="hypSortGLBal_Click"></asp:LinkButton>
</HeaderTemplate>
</asp:TemplateField>
...Other Columns...
</Columns>
<PagerStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:GridView>
<asp:HiddenField ID="hdnPrepPopulated" runat="server" />
</asp:Panel>

Pre Sort GridView Items

I have a aspGridView Control. I am only using it to display information and it does not allow the user to filter. I would like to preset the information where it displays it using a descending sort on the column read_date. Can I do this from the controllers settings?
<asp:GridView AllowPaging="true" runat="server" ID="gridRead" AutoGenerateColumns='false' BorderStyle="None" GridLines="None" HorizontalAlign="Center" Width="200px" PageSize="12" >
<PagerSettings Visible="false" />
<Columns>
<asp:BoundField
HeaderText="Date"
HeaderStyle-HorizontalAlign="Left"
DataField="read_date"
Visible="true"
DataFormatString="{0:d}"
ItemStyle-HorizontalAlign="Left"
HeaderStyle-ForeColor="#004C7E"
HeaderStyle-Font-Underline="true"
ItemStyle-ForeColor="#004C7E"
ItemStyle-Font-Size="Medium"
/>
<asp:BoundField
HeaderText="Reading"
HeaderStyle-HorizontalAlign="Left"
DataField="reading"
Visible="true"
DataFormatString="{0:C}"
ItemStyle-HorizontalAlign="Left"
HeaderStyle-ForeColor="#004C7E"
HeaderStyle-Font-Underline="true"
ItemStyle-ForeColor="#004C7E"
ItemStyle-Font-Size="Medium"
ItemStyle-CssClass="datagridStyle"
/>
So I just want to display the grid with read_date descending. I am binding a DataSet to this grid. Thanks
Set the "order by" command in your stored procedure.

change Width Gridview While containing 100 words;

HTML
<asp:GridView ID="GridView1" runat="server" GridLines="Vertical" Width="825px" AutoGenerateColumns="False"
DataSourceID="LinqDataSource1">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="True"
SortExpression="Title" />
<asp:BoundField DataField="Body" HeaderText="Body" ReadOnly="True" ItemStyleWidth="1"
SortExpression="Body"></asp:BoundField>
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataClassesDataContext"
Select="new (Title, Body)" TableName="PrivateMessages">
</asp:LinqDataSource>
Code
GridView1.Columns[1].ItemStyle.Width = 1;
i would like Fixed Columns[1].width=1 ; While Body containing 100 words;
This Code Does Not Change Width Gridview?
It's not necessary to change the GridView with drag and drop. You have to just select its edges and you can change it.

Getting rowID value for a "checked" checkbox in GridView in ASP.Net

I am using checkboxs in a GridView. I need to determine the value in the cell in the 2nd column, if a checkbox has been checked.
I am using C# 2008 and ASP.net
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="False" CellPadding="4" GridLines="None" Width="100%" AllowPaging="True" PageSize="20"
onpageindexchanging="gvOrders_PageIndexChanging" ForeColor="#333333">
<Columns>
<asp:TemplateField HeaderText="VerifiedComplete" >
<ItemTemplate>
<asp:CheckBox ID="cbPOID" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PurchaseOrderID" HeaderText="PurchaseOrderID" HtmlEncode="False" ></asp:BoundField>
<asp:BoundField DataField="VENDOR_ID" HeaderText="Vendor ID"></asp:BoundField>
<asp:BoundField DataField="VENDOR_NAME" HeaderText="Vendor Name"></asp:BoundField>
<asp:BoundField DataField="ITEM_DESC" HeaderText="Item Desc"></asp:BoundField>
<asp:BoundField DataField="SYS_DATE" HeaderText="System Date"></asp:BoundField>
</Columns>
<FooterStyle CssClass="GridFooter" BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle CssClass="GridPager" ForeColor="#333333" BackColor="#FFCC66" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle CssClass="GridHeader" BackColor="#990000" Font-Bold="True" ForeColor="White" />
<RowStyle CssClass="GridItem" BackColor="#FFFBD6" ForeColor="#333333" />
<AlternatingRowStyle CssClass="GridAltItem" BackColor="White" />
</asp:GridView>
protected void btnDisable_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvOrders.Rows)
{
if (((CheckBox)gvr.FindControl("cbPOID")).Checked == true)
{
string strPrimaryid = gvr.Cells[2].ToString();
}
}
}
Another way to do this, to avoid accessing the cells of the GridView by index, is to convert the desired BoundField to a TemplateField in the designer. Then use the FindControl method to get the text value in that cell. By default, the designer will give the Label control of the new TemplateField a name like "Label1."
I would add some pictures to show the designer part, if that process were easier. At any rate, the aspx would change like so, which you could do manually too:
<asp:BoundField DataField="PurchaseOrderID" ...</asp:BoundField>
becomes
<asp:TemplateField HeaderText="PurchaseOrderID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("PurchaseOrderID") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("PurchaseOrderID") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
Then you would make this simple code change:
string strPrimaryid = gvr.FindControl("Label1").Text;
However, I think a better way to do this is by utilizing the DataKeys features of the GridView control. The first step would be to set the DataKeyNames property of your GridView:
<asp:GridView ID="gvOrders" runat="server" DataKeyNames="PurchaseOrderID" ...>
Then, assuming your PurchaseOrderID column is of type int, you would change that same line to be:
int primaryid = (int)gvOrders.DataKeys[gvr.RowIndex].Value;

Categories