Why this code doesn't output anything to label? - c#

<asp:GridView runat="server" ID="gridUserAccounts" SkinID="gridviewSkin" PageSize="5">
<Columns>
<asp:BoundField HeaderText="User Name" DataField="UserName" />
<asp:BoundField HeaderText="Email" SortExpression="Email" DataField="Email" />
<asp:BoundField HeaderText="Last Login Date" SortExpression="LastLoginDate" DataField="LastLoginDate" />
<asp:BoundField HeaderText="Last Activity Date" SortExpression="LastActivityDate" DataField="LastActivityDate" />
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" NavigateUrl='<%# string.Format("manage-user-detail.aspx?UserName={0}", Eval("UserName")) %>' ID="linkNavigate" Text="View Detail" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind for this is
if (!Page.IsPostBack)
{
gridUserAccounts.DataSource = Membership.GetAllUsers();
gridUserAccounts.DataBind();
}
Now, at 'manage-user-detail.aspx' page i am catching the query string but it doen't work like this
if (!IsPostBack)
{
string userKey1 = Request.QueryString["UserName"];
Guid UserID = new Guid(Membership.GetUser(userKey1).ProviderUserKey.ToString());
//Guid userKey = new Guid(userKey1);
MembershipUser mu = Membership.GetUser(UserID);
//string userName = mu.UserName;
lblKey.Text = mu.UserName;
}
Nothing is showing up in label. Why?

I solve the problem with following code
string userName = Membership.GetUser(Request.QueryString["UserName"].ToString()).UserName;
statusLabel.Text = userName;

From my experience the only way to get the querystring is like so:
Request.QueryString.Item("UserName");
I see that in your code you left out Item.

Related

selectedrow on hidden boundfield

I've done my research here and I can now succesfully get a value of a hidden boundfield column in my gridview. The problem is I can't target the a hidden column of the row that I selected.
can I use GridView1.SelectedRow.Cells[7].Text; something like that on a hidden column.Is it possible?
here is my code:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//GridView1.Columns[7].Visible = true;
//stock_id_gridview_1();
foreach (GridViewRow row in GridView1.Rows)
{
string id = GridView1.DataKeys[row.RowIndex]["id"].ToString();
con.Open();
cmd = new SqlCommand(#"SELECT transaction_id,transaction_number
FROM stocks_history
WHERE id = #id", con);
cmd.Parameters.AddWithValue("#id", id);
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
transaction_id = rdr["transaction_id"].ToString();
//lbl_test_id.Text = rdr["transaction_id"].ToString();
transaction_number = rdr["transaction_number"].ToString();
lbl_test_id.Text = transaction_id + " " + transaction_number;
}
}
con.Close();
}
here is my gridview:
<asp:GridView ID="GridView1"
CssClass="table table-hover table-striped"
runat="server"
AutoGenerateColumns="False" DataKeyNames="id" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="productName" HeaderText="Product Name"
SortExpression="DateField" />
<asp:BoundField DataField="stock_name" HeaderText="Stock Name"
SortExpression="DateField" />
<asp:BoundField DataField="stock_id" HeaderText="Stock I.D."
SortExpression="DateField" />
<asp:BoundField DataField="stock_in" HeaderText="Stock In"
SortExpression="DateField" />
<asp:BoundField DataField="stock_out" HeaderText="Stock Out"
SortExpression="DateField" />
<asp:BoundField DataField="stock_on_hand" HeaderText="On hand"
SortExpression="DateField" />
<asp:BoundField DataField="max_date" HeaderText="Date & Time"
DataFormatString="{0:MM-dd-yyyy hh:mm tt}"
SortExpression="DateField" />
<asp:BoundField DataField="id" Visible="false" HeaderText="id"
SortExpression="DateField" />
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"
Value='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" ControlStyle-CssClass="btn btn-info btn-sm" CommandName="Select" ItemStyle-Width="150" HeaderText="Review">
<ControlStyle CssClass="btn btn-info btn-sm"></ControlStyle>
<ItemStyle Width="150px"></ItemStyle>
</asp:ButtonField>
</Columns>
</asp:GridView>
I wanted to target this bound field:
<asp:BoundField DataField="id" Visible="false" HeaderText="id"
SortExpression="DateField" />
If You use attribute DataKeyNames, you can take value from invisible column like
Use Attribute
<asp:GridView runat="server" ID="GridView" DataKeyNames="id">
</asp:GridView>
And you can access the data
var id = GridView.DataKeys[RowIndex].Values[KeyIndex]
To get selected row hidden column value
var id = GridView.DataKeys[GridView.SelectedRow.RowIndex].Values[0];

Not able to access hyperlink column inside gridview from code behind

I want to access the HyperLinkField column of the GridView from code behind but I am unable to do so.
I have the column in my dataset but I am still not able to use it.
My HyperLinkField column is named Status.
Here is what I tried:
UltraWebGrid1.DataSource = ObjPriDsGrid;
UltraWebGrid1.DataBind();
string StrPriStatus = "";
for (int IntPriI = 0; IntPriI < UltraWebGrid1.Rows.Count; IntPriI++)
{
if (UltraWebGrid1.Rows[IntPriI].Cells[6].Text.Trim() != null)
{
StrPriStatus = UltraWebGrid1.Rows[IntPriI].Cells[6].Text.Trim();
}
else
{
}
if (StrPriStatus == "5")
{
UltraWebGrid1.Rows[IntPriI].Cells[8].Text = ""; // Not getting status column here
}
}
Here is my GridView:
<asp:GridView ID="UltraWebGrid1" ShowHeader="true" runat="server" AutoGenerateColumns="false"
DataKeyNames="mkey" OnRowDataBound="Grid_RowDataBound" Width="98%" Height="30%"
PageSize="10" AllowPaging="true" OnPageIndexChanging="Grid1_PageIndexChanging"
ShowFooter="true" CssClass="Grid">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../../../Images/plus.png" />
<asp:Panel ID="pnlGrid" runat="server" Style="display: none">
<asp:GridView ID="Grid2" runat="server" AutoGenerateColumns="false" Width="600px"
CssClass="ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="80px" DataField="RefMkey" HeaderText="Mkey" />
<asp:BoundField ItemStyle-Width="150px" DataField="CurrentUser" HeaderText="Current User" />
<asp:BoundField ItemStyle-Width="180px" DataField="Department" HeaderText="Current Department" />
<asp:BoundField ItemStyle-Width="100px" DataField="remarks" HeaderText="Remarks" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="0px" DataField="mkey" Visible="false" HeaderText="Mkey" />
<asp:BoundField ItemStyle-Width="8%" DataField="Doc_No" HeaderText="IW/ No" />
<asp:BoundField ItemStyle-Width="10%" DataField="Doc_Date" HeaderText="IW/ Date" />
<asp:BoundField ItemStyle-Width="12%" DataField="DocType" HeaderText="Doc type" />
<asp:BoundField ItemStyle-Width="15%" DataField="Party_Name" HeaderText="Party Name" />
<asp:BoundField ItemStyle-Width="0" Visible="true" DataField="Status_Flag" HeaderText="Status" />
<asp:BoundField ItemStyle-Width="10%" DataField="LastAction_datetime" HeaderText="Last Action Date" />
<asp:BoundField ItemStyle-Width="10%" DataField="CurrStatus" HeaderText="Current Status" />
<asp:BoundField ItemStyle-Width="10%" DataField="Type_desc" HeaderText="Resp Dept" />
<asp:BoundField ItemStyle-Width="12%" DataField="UserName" HeaderText="Resp User" />
<asp:BoundField ItemStyle-Width="8%" DataField="No_Of_Days" HeaderText="No of days" />
<asp:HyperLinkField ItemStyle-Width="5%" DataNavigateUrlFields="Mkey, Status, Doc_No"
DataNavigateUrlFormatString="~/Administration/Dispatch/Inward/FrmInwardNextAction.aspx?Inward_mkey={0}&Status={0}&IWNO={0}"
HeaderText="Status" DataTextField="Status" Target="_blank" />
<asp:HyperLinkField ItemStyle-Width="5%" DataNavigateUrlFields="Mkey, Status, Doc_No"
HeaderText="View" DataTextField="View" Target="_blank" DataNavigateUrlFormatString="~/Administration/Dispatch/Inward/InwardDocDetails.aspx?Key={0}&Status={0}&IWNO={0}" />
</Columns>
</asp:GridView>
Columns like HyperLinkField and CheckBoxField behave a little differently than BoundField. They don't just simply contain text like BoundField. You have to get the control within the cell. You can get the child controls of the cell using the Controls collection. We know that specifically for a HyperLinkField, the HyperLink will be the first control in the collection.
HyperLink hyp = (HyperLink)UltraWebGrid1.Rows[IntPriI].Cells[12].Controls[0];
Can you try it like this
if (StrPriStatus == "5")
{
HyperLink HyperLinkObj = (HyperLink)UltraWebGrid1.Rows[IntPriI].Cells[12].Controls[0];
HyperLinkObj.Text = "";
}

DataTable must be set prior to using DataView

Hi i did look at search result for " DataTable must be set prior to using DataView." but none of their solutions fixed my problem or pointed me in the right direction.
Were am i going wrong here, when i press a header to sort out the gridview table i just get an error and no sorting. The error is the same as my title for this post.
EDIT: Not sure if its relevant but i populate the gridview on page load from a MS SQL database
Mark-up
<asp:GridView ID="_propertyGridView" runat="server" CssClass="table table-hover table-striped" AutoGenerateColumns="false" AllowSorting="true" GridLines="None" OnRowCommand="PropertyRowCommand" Width="100%">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Ref" SortExpression="Id" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="PostCode" HeaderText="Post Code" SortExpression="PostCode" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="ContractsFinishedOn" HeaderText="Contract Signed On" SortExpression="ContractsFinishedOn" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Mobile" HeaderText="Mobile No." SortExpression="Mobile" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="LandLordEmail" HeaderText="Owners Email" SortExpression="LandLordEmail" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="MoveInDate" HeaderText="Move In Date" SortExpression="MoveInDate" HeaderStyle-HorizontalAlign="Left" />
<asp:TemplateField HeaderText="Status" SortExpression="Status1">
<ItemTemplate>
<asp:CheckBox ID="_tenantPaymentCheckBox" runat="server" Enabled="false" Checked='<%#Bind("TenantReceipt") %>' />
<asp:LinkButton ID="_tenantPaymentLink" Text="Send Tenant Receipt" CommandArgument='<%#Bind("Id") %>' CommandName="TenantEmail" runat="server" OnClientClick="javascript:return confirm('This will email & sms the tenant, please make sure its correct');" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" SortExpression="Status2">
<ItemTemplate>
<asp:CheckBox ID="_landlordInfoCheckBox" runat="server" Enabled="false" Checked='<%#Bind("LandlordInfo") %>' />
<asp:LinkButton ID="_landlordInfoLink" Text="Request Landlord Info" CommandArgument='<%#Bind("Id") %>' CommandName="LandlordInfoEmail" runat="server" OnClientClick="javascript:return confirm('This will email & sms the landlord, please make sure its correct');" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" SortExpression="Status3">
<ItemTemplate >
<asp:CheckBox ID="_landlordRentCheckBox" runat="server" Enabled="false" Checked='<%#Bind("LandlordReceipt") %>' />
<asp:LinkButton ID="_landlordRentLink" Text="Send Landlord Receipt" CommandArgument='<%#Bind("Id") %>' CommandName="LandlordEmail" runat="server" OnClientClick="javascript:return confirm('This will email & sms the landlord, please make sure its correct');" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-Behind
protected void _propertyGridView_Sorting(object sender, GridViewSortEventArgs e)
{
try
{
string sortExpression = e.SortExpression;
ViewState["z_sortexpresion"] = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, "DESC");
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, "ASC");
}
}
catch (Exception ex)
{
SearchErrorLbl.Text = "error in such";
}
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set
{
ViewState["sortDirection"] = value;
}
}
private void SortGridView(string sortExpression, string direction)
{
DTSorting = new DataView(DTSorting, "", sortExpression + " " + direction, DataViewRowState.CurrentRows).ToTable();
_propertyGridView.DataSource = DTSorting;
_propertyGridView.DataBind();
}
public DataTable DTSorting
{
get
{
if (ViewState["Sorting"] != null)
return (DataTable)ViewState["Sorting"];
else
return null;
}
set
{
ViewState["Sorting"] = value;
}
}
Seems to me that the problem is within SortGridView method. You try to use the very same DTSorting property you attempt to set as the table constructor parameter. If it is null at this point it will most definitely throw an exception. DataView needs an existing DataTable instance to work with.
I should also mention that the current implementation will likely create multiple DataTable instances that won't ever get disposed of. One thing for sure is that you aren't disposing of the DataView object you are creating so that you get your sorted table.
If I were you I would rethink how data should be bound. Storing a DataTable object in ViewState is bad practice. The full table will be serialized back and forth between the client and the server, resulting in performance loss.
I suggest you read about it here: View State Overview

ASP.NET Gridview ItemTemplate Access in CodeBehind

I am having trouble accessing an asp.NET HiddenField from a Gridview ItemTemplate in the codebehind. I need to be able to read the values that these hiddenfields contain so that I can execute the delete method.
The code is as follows
<%# Control Language="C#" AutoEventWireup="true" CodeFile="MemberList.ascx.cs" Inherits="UserControls_MemberList" %>
<asp:RadioButtonList ID="ReportSelect" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="1">All</asp:ListItem>
<asp:ListItem Value="2">Current Members</asp:ListItem>
<asp:ListItem Value="3">Perspective Members</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="ReportSelectButton" runat="server" OnClick="ReportSelectButton_Click"
Text="Select Report Type" />
<asp:Button ID="LinkToHomePage" runat="server" Text="Back to Homepage" OnClick="LinkToHomePage_Click">
</asp:Button>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Height="308px"
Width="1282px" onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField HeaderText="First Name" AccessibleHeaderText="FirstName" DataField="FirstName">
</asp:BoundField>
<asp:BoundField HeaderText="Last Name" AccessibleHeaderText="LastName" DataField="LastName">
</asp:BoundField>
<asp:BoundField HeaderText="Street Address" AccessibleHeaderText="StreetAddress"
DataField="StreetAddress"></asp:BoundField>
<asp:BoundField HeaderText="City" AccessibleHeaderText="City" DataField="City"></asp:BoundField>
<asp:BoundField HeaderText="State" AccessibleHeaderText="State" DataField="State">
</asp:BoundField>
<asp:BoundField HeaderText="Zip" AccessibleHeaderText="Zip" DataField="Zip"></asp:BoundField>
<asp:BoundField HeaderText="Birthday" AccessibleHeaderText="Birthday" DataField="Birthday" />
<asp:BoundField HeaderText="Email" AccessibleHeaderText="Email" DataField="Email">
</asp:BoundField>
<asp:BoundField HeaderText="PrimaryPhone" AccessibleHeaderText="PrimaryPhone" DataField="PrimaryPhone" />
<asp:BoundField HeaderText="AlternatePhone" AccessibleHeaderText="AlternatePhone"
DataField="AlternatePhone" />
<asp:BoundField HeaderText="Pending" AccessibleHeaderText="Pending" DataField="Pending" />
<asp:BoundField HeaderText="IsMember" AccessibleHeaderText="IsMember" DataField="IsMember" />
<asp:BoundField HeaderText="Username" AccessibleHeaderText="Username" DataField="Username">
</asp:BoundField>
<asp:BoundField HeaderText="Description" AccessibleHeaderText="Descripton" DataField="Description" />
<asp:TemplateField HeaderText="Edit" AccessibleHeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="EditUsername" runat="server" NavigateUrl='<%# Link.ToMemberAdmin(Eval("Username").ToString())%>'
Text="Edit" />
<asp:Button ID="DeleteButton" runat="server" Text="Delete Entry" OnClick="DeleteButton_Click"/>
<asp:HiddenField ID="HiddenUsername" Value='<%#Bind("Username") %>' runat="server" />
<asp:HiddenField ID="HiddenEmail" Value='<%#Bind("Email") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind
protected void DeleteButton_Click(object sender, EventArgs e)
{
HiddenField Username = GridView1.FindControl("HidderUsername") as HiddenField;
HiddenField Email = GridView1.FindControl("HiddenEmail") as HiddenField;
string username = Username.Value;
string email = Email.Value;
AdminAccess.DeleteMemberApplication(username, email);
}
Any help would be greatly appreciated.
The HiddenField controls are going to be part of a <td> which is one of the <tr> the GridView renders. The GridView control's FindControl only knows of it's immediate children and as the Hidden controls are two levels below that, it's not going to find them. Instead, start from the sender and try to find its sibling Hidden controls. Replace the two HiddenControl lines in the event handler as below:
HiddenField Username = (HiddenField) ((Button)sender).Parent.Controls.FindControl("HiddenUsername");
HiddenField Email = (HiddenField) ((Button)sender).Parent.Controls.FindControl("HiddenEmail");
And it should get the values you are looking for to delete the data in that row.
Just use CommandArgument of button
<asp:TemplateField HeaderText="Edit" AccessibleHeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="EditUsername" runat="server" NavigateUrl='<%# Link.ToMemberAdmin(Eval("Username").ToString())%>'
Text="Edit" />
<asp:Button ID="DeleteButton" runat="server" Text="Delete Entry" OnClick="DeleteButton_Click"
CommandArgument='<%#Eval("Username")+"^"+Eval("Email") %>'/>
</ItemTemplate>
</asp:TemplateField>
protected void DeleteButton_Click(object sender, EventArgs e)
{
var btn = sender as Button;
var args = btn.CommandArgument.Split('^');
string username = args[0];
string email = args[1];
AdminAccess.DeleteMemberApplication(username, email);
}

Value from row with DropDownList on DropDownList Index Changed Event

Code:
<asp:GridView ID="gv_Recruit" AutoGenerateColumns="False" Width="100%"
runat="server" OnRowCreated="gvStates_RowCreated"
OnRowDataBound="gvStates_RowCreated">
<Columns>
<asp:BoundField HeaderText="key" DataField="key" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Quota" DataField="Quota" />
<asp:BoundField HeaderText="Session" DataField="Sess" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:DropDownList ID="ddlCities" Width="100%" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddl_selected">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Recruiter" DataField="Recruiter" />
<asp:BoundField HeaderText="MN Phone" DataField="MN Phone" />
<asp:BoundField HeaderText="Cell Phone" DataField="Cell Phone" />
</Columns>
</asp:GridView>
Code Behind:
protected void ddl_selected(object sender, EventArgs e)
{
string _dd_value = ((DropDownList)sender).SelectedValue;
string trying_to_get = gv_Recruit.Rows[???].Cells[0].Text.ToString();
string also_tried = gv_Recruit.SelectedRow.Cells[0].Text.ToString();
}
Basically what I'm trying to do is get the key value from the first row when the drop down is changed so I can perform an update ???
Can't figure this out.
Thanks in advance for the help...
Try
GridViewRow gRow = (GridViewRow)(sender as Control).Parent.Parent;
string trying_to_get = string.Empty;
if (gRow != null)
{
trying_to_get = gRow.Cells[0].Text;
}

Categories

Resources