Ryan McSorley Ryan McSorley - 2 years ago 109
ASP.NET (C#) Question

'username' does not exist in it's current context

The ID is inside the

and it cannot be found in the code file.

<form id="form1" runat="server">
<asp:SqlDataSource ID="searchresults" runat="server"
ConnectionString='<%$ ConnectionStrings:AgileDatabaseConnection %>'
SelectCommand=" SELECT [userID], [userName], [firstName],[lastName],[password], [email] FROM [Users] WHERE ([email] LIKE '%' + @email + '%')">
<asp:querystringparameter querystringfield="searchquery" name="email" type="String"></asp:querystringparameter>

<asp:ListView ID="displayitems" runat="server" DataSourceID="searchresults">
<asp:label runat="server" associatedcontrolid="projectOwner" cssclass="col-md-2 control-label">Project Owner:</asp:label>
<div class="col-md-10">
<asp:TextBox runat="server" ID="ProjectOwner" CssClass="form-control" /><br />
<asp:label runat="server" associatedcontrolid="projectOwner" cssclass="col-md-2 control-label">Scrum Master:</asp:label>
<div class="col-md-10">
<asp:SqlDataSource ID="ScrumMaster" runat="server" ConnectionString='<%$ ConnectionStrings:AgileDatabaseConnection %>' SelectCommand="SELECT userName FROM [Users]"></asp:SqlDataSource>
<asp:dropdownlist runat="server" id="usertype" DataSourceID="ScrumMaster" DataTextField="userName"></asp:dropdownlist><br />

<asp:label runat="server" cssclass="col-md-2 control-label">Email:</asp:label>
<asp:Label Text='<%#Eval("email") %>' runat="server" ID="emaillabel" /><br />
<asp:label runat="server" cssclass="col-md-2 control-label">UserName:</asp:label>
<asp:Label Text='<%#Eval("userName") %>' runat="server" ID="username" /><br />

<asp:label runat="server" cssclass="col-md-2 control-label">UserID:</asp:label>
<asp:Label runat="server" Text='<%#Eval("userID") %>' ID="UserID" CssClass="form-control" />
<br />
<div class="actions"></div>

<asp:Button Text="Add" runat="server" class="btn pull-right" ID="uploadbutton" OnClick="add_Click"></asp:Button>

<span>No users match <asp:Label Text='' runat="server" ID="email" /> .</span>


C# says it can't find 'userName'. Here's my backend code:

string ownerName = ProjectOwner.Text;
string IDuser = username.Text;
string IDdata = Session["userID"].ToString();

How do I get the userName value through?

Answer Source

The problem is that ListView can return more then one item, so code behind doesn't know about which of the itens controls (username and ProjectOwner) are you talking about.

If you want to do the same thing for EACH item, you can do like this:

protected void displayitems_ItemDataBound(object sender, ListViewItemEventArgs e)
    if (e.Item.ItemType == ListViewItemType.DataItem)
        string ownerName = ((TextBox)e.Item.FindControl("ProjectOwner")).Text;
        string IDuser = ((Label)e.Item.FindControl("username").Text;
        string IDdata = Session["userID"].ToString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download