Access control id with OnItemDataBound property in c# - c#

I have this nested datalist.
EDIT
<asp:DataList ID="mydatalist" DataKeyField="sid" ItemStyle-CssClass="lft_c_down" runat="server">
<ItemTemplate>
<div class="wholeC">
<div class="ctop">
<div class="lft_l">
<div class="lft_l_top">
<asp:Image ID="Image1" runat="server" ImageUrl='<%#DataBinder.Eval(Container.DataItem,"ipath")%>' Height="245px" Width="297px" />
<br/>
</div>
</div>
<div class="lft_r">
<asp:Label ID="lbl_sid" Text='<%#DataBinder.Eval(Container.DataItem,"sid") %>' runat="server" Visible="false" />
<b class="products" >Product Name:</b>
<asp:Label ID="lbl2" Text='<%#DataBinder.Eval(Container.DataItem,"ipath") %>' runat="server" />
<br/>
<b class="products">Brand:</b>
<asp:Label ID="lbl1" Text='<%#DataBinder.Eval(Container.DataItem,"brand") %>' runat="server" />
<br/>
</div>
</div>
<div class="cdown">
<asp:TextBox ID="tb_cmt" runat="server" Height="35px" Width="500px" placeholder="comment.." />
<asp:Button ID="Button1" runat="server" Text="Comment" backcolor="black" BorderStyle="None" Font-Names="Consolas" Font-Overline="False"
ForeColor="White" Height="34px" Width="108px" OnClick="cmt_Click" />
<asp:DataList ID = "dl_cmt" runat="server">
<ItemStyle CssClass="coment" />
<ItemTemplate>
<asp:Label ID="lblcmt" runat="server" Text='<%#Eval("ecomment")%>' />
<asp:Label ID="lblDate" style=" color:brown; font-family:Cursive; font-size:x-small; " runat="server" Text='<%#Eval("my_date","on {0}") %>' />
</ItemTemplate>
</asp:DataList>
<%--<asp:LinkButton ID="lb_showMore" runat="server">Show More</asp:LinkButton>--%>
</div>
</div>
</ItemTemplate>
</asp:DataList>
It uses the property onItemDataBound.But with its use i am unable to access the id of this datalist.
public void cmtdatabound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
DataList dl = e.Item.FindControl("dl_cmt") as DataList;
string str = gstr;
sq.connection();
SqlCommand cmd = new SqlCommand("select top 4 * from comment where sid='" + str + "' order by my_date desc", sq.con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dl.DataSource = ds;
dl.DataBind();
}
}
Here the dl is null that means the id is not accessible.How do i access the id of the datalist here.

You can use sender parameter as DataList like this:
DataList dl = sender as DataList;

Related

Is there a way to resolve a problem of "SelectedIndex which is invalid" in c#

I am a first year student and I am currently developing a web application base on an ecommerce website. I recently encountered a problem which I cannot resolve while spending weeks on it.
The problem is when I update a product on the app I get an error this says crashes my application.
Here is the Problem.
Exception Details: System.ArgumentOutOfRangeException: 'ddlcat' has a SelectedIndex which is invalid because it does not exist in the list of items.
Parameter name: value
and here my code for the frontend and backend.
frontend:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="maincontent" runat="server">
<div class="form-horizontal">
<h4>Manage product</h4>
<hr />
<div class="col-md-8">
<asp:TextBox runat="server" ID="txtProductid" Visible="false"
CssClass="form-control" />
</div>
<div class="form-group row justify-content-center">
<asp:Label runat="server" CssClass="col-md-2 col-form-label">Select
a Category</asp:Label>
<div class="col-md-8">
<asp:DropDownList ID="ddlcat" runat="server"
CssClass="form-control">
</asp:DropDownList>
</div>
</div>
<div class="form-group row justify-content-center">
<asp:Label runat="server"
CssClass="col-md-2 col-form-label"></asp:Label>
</div>
<div class="form-group row justify-content-center">
<asp:Label runat="server" CssClass="col-md-2 col-form-label">Product name</asp:Label>
<div class="col-md-8">
<asp:TextBox runat="server" ID="txtPname"
CssClass="form-control" />
</div>
</div>
<div class="form-group row justify-content-center">
<asp:Label runat="server"
CssClass="col-md-2 col-form-label">Product Brand</asp:Label>
<div class="col-md-8">
<asp:TextBox runat="server" ID="txtPbrand"
CssClass="form-control" />
</div>
</div>
<div class="form-group row justify-content-center">
<asp:Label runat="server" CssClass="col-md-2 col-form-label">Product price</asp:Label>
<div class="col-md-8">
<asp:TextBox runat="server" ID="txtprice"
CssClass="form-control" />
</div>
</div>
<div class="form-group row justify-content-center">
<asp:Label runat="server"
CssClass="col-md-2 col-form-label">Product Description</asp:Label>
<div class="col-md-8">
<asp:TextBox runat="server" ID="txtPdesc" TextMode="Multiline"
CssClass="form-control" />
</div>
</div>
<div class="form-group row justify-content-center">
<asp:Label runat="server"
CssClass="col-md-2 col-form-label">Product image</asp:Label>
<div class="col-md-8">
<asp:FileUpload ID="fuimage" runat="server" CssClass="" />
<asp:Image ID="Image1" runat="server" Visible="false" Width="75"
Height="100" />
</div>
</div>
<div class="form-group row justify-content-center">
<asp:Label runat="server"
CssClass="col-md-2 col-form-label"></asp:Label>
<div class="col-md-8">
<div class="form-check-inline">
<asp:CheckBox runat="server" ID="chkstatus"
CssClass="form-check-input" />
<asp:Label runat="server"
CssClass="form-check-label">Status</asp:Label>
</div>
</div>
</div>
<div class="form-group row justify-content-center">
<div class="offset-md-2 col-md-8">
<asp:Button runat="server" ID="btnupdate" OnClick="btnupdate_Click" Text="Update Product"
Visible="false" CssClass="btn btn-block btn-outline-primary" />
<asp:Button runat="server" ID="btndelete" OnClick="btndelete_Click" Text="Delete Product"
OnClientClick="return confirm ('Are you sure you want to delete?')"
Visible="false" CssClass="btn btn-block btn-outline-primary" />
<asp:Button runat="server" ID="btncancel" OnClick="btncancel_Click" Text="Cancel"
Visible="false" CssClass="btn btn-block btn-outline-primary" />
<asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
</div>
</div>
</div>
<hr />
<asp:GridView ID="gvs" AutoGenerateColumns="false"
DataKeyNames="P_id"
OnSelectedIndexChanged="gvs_SelectedIndexChanged" ClientIDMode="Static"
Width="800" runat="server">
<HeaderStyle BackColor="#eeeeee" ForeColor="White" Font-Bold="true"
Height="30" />
<AlternatingRowStyle BackColor="#f5f5f5" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtnSelect" runat="server"
CssClass="btn btn-outline-info" CommandName="Select" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Movie Name">
<ItemTemplate>
<!-- display the movie name -->
<asp:Label ID="lblproductname" Text='<%#Eval("P_name")%>'
runat="server" />
</ItemTemplate>
</asp:TemplateField>
<%-- add an imagefield here to display the poster--%>
</Columns>
</asp:GridView>
</asp:Content>
Backend
protected void gvs_SelectedIndexChanged(object sender, EventArgs e) <----------- theproblem is found here --------------------->
{
lblMsg.Text = "";
Image1.Visible = true;
txtProductid.Text =
(gvs.DataKeys[gvs.SelectedIndex].Value.ToString());
txtPname.Text =
((Label)gvs.SelectedRow.FindControl("lblproductname")).Text;
SqlConnection con = new SqlConnection(_conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
//create the movieid parameter
cmd.Parameters.AddWithValue("#pid", txtProductid.Text);
//assign the parameter to the sql statement
cmd.CommandText = "SELECT * FROM tblProduct where P_id = #pid";
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
//retrieving FIELD values and assign the form controls
ddlcat.SelectedIndex = Convert.ToInt32(dr["Category_cat_id"]);
txtPbrand.Text = dr["P_brand"].ToString();
txtPdesc.Text = dr["P_description"].ToString();
txtprice.Text = dr["P_cost"].ToString();
chkstatus.Checked = (Boolean)dr["P_status"];
Image1.ImageUrl = "../image/" + dr["P_image"].ToString();
}
con.Close();
btnupdate.Visible = true;
btndelete.Visible = true;
btncancel.Visible = true;
}
private void ResetAll()
{
btncancel.Visible = false;
btndelete.Visible = false;
btnupdate.Visible = false;
ddlcat.SelectedIndex = 0;
txtPname.Text = "";
txtprice.Text = "";
txtPbrand.Text = "";
txtPdesc.Text = "";
chkstatus.Checked = false;
Image1.ImageUrl = "";
}
Simply if you guys can take a look about it, this would help me greatly.
Thanks in advance

Inserting a record in an SQL Server database using session in aspnet with C#

I'm trying to insert a record into a SQL Server 2014 database using ASP.NET with C#.
I have implemented a session for my gridview data, and I'm trying to insert that session into the database, but when I click the button "book", only the top URL changes:
Database:
The record isn't getting inserted into the database nor my Label (Errorm) is changing to gg.
.aspx file:
<%# Page Title=""
Language="C#"
MasterPageFile="~/Main.Master"
AutoEventWireup="true"
CodeBehind="hotels.aspx.cs"
Inherits="Hotel_Mangement.hotels" %>
<asp:Content ID="Content1" ContentPlaceHolderID="hotels" runat="server">
<div class="destinations">
<div class="destination-head">
<div class="wrap">
<h3>Hotels</h3>
</div>
<!-- End-destinations -->
<div class="find-place dfind-place">
<div class="wrap">
<div class="p-h">
<span>FIND YOUR</span>
<label>HOTEL</label>
</div>
<!-- strat-date-picker -->
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(function () {
$("#<%= txtstart.ClientID %>").datepicker();
});
</script>
<!-- /End-date-picker -->
<!-- strat-date-picker -->
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(function () {
$("#<%= txtend.ClientID %>").datepicker();
});
</script>
<!---/End-date-piker---->
<div class="p-ww">
<form>
<span> City or Area</span>
<asp:DropDownList ID="dl1" runat="server" class="dest" required="This field cannot be blank">
<asp:ListItem Selected="True">Location</asp:ListItem>
<asp:ListItem>Mumbai</asp:ListItem>
<asp:ListItem>Goa</asp:ListItem>
<asp:ListItem>Delhi</asp:ListItem>
<asp:ListItem>Ahmedabad</asp:ListItem>
<asp:ListItem>Jammu</asp:ListItem>
<asp:ListItem>Jharkhand</asp:ListItem>
<asp:ListItem>Kerala</asp:ListItem>
<asp:ListItem>Bhuj</asp:ListItem>
<asp:ListItem>Bengaluru</asp:ListItem>
<asp:ListItem>Kalyan</asp:ListItem>
</asp:DropDownList><br />
<br /><span> Check-in</span>
<asp:TextBox ID="txtstart" runat="server" class="date" required="This field cannot be blank"></asp:TextBox>
<span> Check-out</span>
<asp:TextBox ID="txtend" runat="server" class="date" required="This field cannot be blank"></asp:TextBox><br /> <br />
<span> Number of rooms</span>
<asp:DropDownList ID="dlrooms" runat="server" required="This field cannot be blank">
<asp:ListItem Selected="True">Select number of rooms</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:DropDownList><br /><br />
<span> Number of members</span>
<asp:DropDownList ID="dlmumbers" runat="server" required="This field cannot be blank">
<asp:ListItem Selected="True">Select number of members per room</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
</asp:DropDownList>
<br /> <br />
<asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
</form>
</div>
<div class="clear"> </div>
</div>
</div>
<!----//End-find-place---->
</div>
<div class="criuse-main">
<div class="wrap">
<div class="criuse-head1">
<h3>CHEAPEST HOTELS</h3>
</div>
</div>
</div>
<asp:SqlDataSource ID="SqlDataSource1"
runat="server"
ConnectionString='<%$ ConnectionStrings:RegisterConnectionString15 %>'
SelectCommand="SELECT * FROM [hotels_main]"></asp:SqlDataSource>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" >
<ItemTemplate>
<div ID="div1" runat="server">
<div class="criuse-main" >
<div class="wrap">
<div class="criuse-grids">
<div class="criuse-grid">
<div class="criuse-grid-head">
<div class="criuse-img">
<div class="criuse-pic">
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("ImagePath") %>' Height="350px" width="1000px"/>
</div>
<div class="criuse-pic-info">
<div class="criuse-pic-info-top">
<div class="criuse-pic-info-top-weather">
<p>33<label>o</label><i>c</i><span> </span></p>
</div>
<div class="criuse-pic-info-top-place-name">
<h2><span><%#Eval("hotel_location") %></span></h2>
</div>
</div>
<div class="criuse-pic-info-price">
<p><span>Starting From</span> <h4><%#Eval("price") %> $</h4></p>
</div>
</div>
</div>
<div class="criuse-info">
<div class="criuse-info-left">
<ul>
<li><a class="c-hotel" href="#"><span> </span><%#Eval("rooms_available") %></a></li>
<li><a class="c-air" href="flight.aspx"><span> </span> Air Ticket</a></li>
<li><a class="c-fast" href="#"><span> </span> Guest per room:<%#Eval("max_guest") %></a></li>
<li><a class="c-car" href="#"><span> </span> Car for All transfers</a></li>
<div class="clear"> </div>
</ul>
</div>
<div class="clear"> </div>
</div>
</div>
<div class="criuse-grid-info">
<h1> <a href="hotels_main.aspx?id=<%#Eval("hotel_id") %>" ><%#Eval("hotel_name") %></a></h1>
<p><%#Eval("s_desc") %> </p>
</div>
</div>
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
<center>
<div>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" class="myGridClass" AutoGenerateColumns="False">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
<Columns>
<asp:TemplateField HeaderText="HotelName">
<ItemTemplate>
<asp:Label ID="lblhotelname" runat="server" Text='<%# Bind("hotel_name") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HotelLocation">
<ItemTemplate>
<asp:Label ID="lblhotellocation" runat="server" Text='<%# Bind("hotel_location") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblprice" runat="server" Text='<%# Bind("price") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
<br />
<form>
<asp:Button ID="book" runat="server" Text="Book now" class="d-next" OnClick="book_Click" />
</form>
<asp:Label ID="lprice" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:Label ID="lcheckin" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:Label ID="lcheckout" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:Label ID="lmembers" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:Label ID="lrooms" runat="server" Text="Label" Visible="False"></asp:Label>
<br />
<asp:Label ID="Errorm" runat="server" Text="Label"></asp:Label>
</div>
</center>
</div>
</asp:Content>
.aspx.cs code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace Hotel_Mangement
{
public partial class hotels : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=RISHIK\SQLEXPRESS;Initial Catalog=Register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
GridView1.Visible = false;
/* div1.Visible = true; */
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from hotels_main";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
book.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
string query =
"select hotel_name, hotel_location ,price from hotels_main where hotel_location='" +
dl1.Text + "' ";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.Visible=true;
con.Close();
if (ds.Tables[0].Rows.Count == 0)
{
Label1.Visible = true;
Label1.Text = "No data found";
book.Visible = false;
}
else
{
/* div1.Visible = true;*/
Label1.Visible = false;
book.Visible = true;
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("HotelName", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("HotelLocation", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Price", typeof(String)));
foreach (GridViewRow row in GridView1.Rows)
{
Label lblhotelname = (Label)row.FindControl("lblhotelname");
Session["hotelname"] = lblhotelname.Text;
Label lblhotellocation = (Label)row.FindControl("lblhotellocation");
Session["hotelocation"] = lblhotellocation.Text;
Label lblprice = (Label)row.FindControl("lblprice");
Session["price"] = lblprice.Text;
dr = dt.NewRow();
dr[0] = lblhotelname.Text;
dr[1] = lblhotellocation.Text;
dr[2] = lblprice.Text;
dt.Rows.Add(dr);
}
Session["check_in"] = txtstart.Text.ToString();
Session["check_out"] = txtend.Text.ToString();
}
}
/*private void SendGridInfo()
{
}
Session["GridData"] = dt; Response.Redirect("WebForm2.aspx");
} */
protected void book_Click(object sender, EventArgs e)
{
con.Open();
string insertQuery = "Insert into hotelbook_details values('" + Session["USER_ID"].ToString() + "','" + Session["hotelname"].ToString() + "','" + Session["hotelocation"].ToString() + "','" + Session["check_in"].ToString() + "','" + Session["check_out"].ToString() + "','" + Session["price"].ToString() + "')";
SqlCommand cmd1 = new SqlCommand(insertQuery, con);
cmd1.ExecuteNonQuery();
con.Close();
Errorm.Text = "gg";
}
}
}
The problem was the <form> ..... </form> tag in aspx. As I am using a master page I don't need it.
After removing all the form tags, it worked all fine.
Are you sure it is not saving? Have you checked your database?
Change your load page to:
if (IsPostBack == false){
GridView1.Visible = false;
/* div1.Visible = true; */
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from hotels_main";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
book.Visible = false;
}
When you click a button it will reload the form load. The code above will prevent it from loading when doing a post-back, that is, clicking a button.

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

The ID is inside the ItemTemplate 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 + '%')">
<selectparameters>
<asp:querystringparameter querystringfield="searchquery" name="email" type="String"></asp:querystringparameter>
</selectparameters>
</asp:SqlDataSource>
<asp:ListView ID="displayitems" runat="server" DataSourceID="searchresults">
<itemtemplate>
<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 />
</div>
</div>
<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>
</div>
</itemtemplate>
</asp:ListView>
<emptydatatemplate>
<span>No users match <asp:Label Text='' runat="server" ID="email" /> .</span>
</emptydatatemplate>
</form>
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?
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();
}
}

The name ' ' does not exist in the current context

The name 'Label2.Text' does not exist in the current context
Catalog.aspx
<asp:DataList ID="DataList1" runat="server" DataKeyField="Id" DataSourceID="SqlDataSource1" RepeatColumns="4" RepeatLayout="Flow">
<ItemTemplate>
<div class="Item">
<div class="name">
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
</div>
<div>
Код:<asp:Label ID="Label2" runat="server" Text='<%# Eval("Id") %>' />
</div>
<img src="<%# Eval("Image") %>" height="115" alt="item"/>
<div class="price">
Цена:
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price")%>' />p.
<asp:Button ID="Button2" runat="server" ForeColor="Black"
onclick="Button2_Click" Text="В КОРЗИНУ" />
</div>
<div class="desc">
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' />
</div>
</div>
</ItemTemplate>
</asp:DataList>
Catalog.aspx.cs
sqlCon.Open();
SqlCommand cmd_SQL = new SqlCommand("INSERT INTO Cart(ClientId,ProductId,Amount) VALUES (#ClientId,#ProductId,#Amount)", sqlCon);
cmd_SQL.Parameters.Add("#ClientId", SqlDbType.NVarChar).Value =Membership.GetUser().ProviderUserKey.ToString();
cmd_SQL.Parameters.Add("#ProductId", SqlDbType.NVarChar).Value =Label2.Text;
cmd_SQL.Parameters.Add("#Amount", SqlDbType.NVarChar).Value = 1;
cmd_SQL.CommandType = CommandType.Text;
cmd_SQL.ExecuteNonQuery();
The name 'Label2.Text' does not exist in the current context
Your label is inside of an item template, which means you cannot just access it any old place on the page. If you want to gain access to the value inside the label, then you need to tie into one of the DataList events, such as OnItemCommand (if you wanted to access the value as the result of a command button click, for instance). You can use FindControl inside of the event handler to access the value. For example:
<asp:DataList runat="server" ID="test" OnItemCommand="test_ItemCommand">
<ItemTemplate>
<asp:Label runat="server" ID="Label2" Text="Test" />
</ItemTemplate>
</asp:DataList>
protected void test_ItemCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
{
if (e.Item != null)
{
var label2 = e.Item.FindControl("Label2");
if (label2 != null && label2 is Label)
{
var productID = ((Label)label2).Text;
// now you have the contents of the label's text property
}
}
}

Passing values from Grid-View inside Modal popup Extender to the text box of parent form

I have a form with some text boxes and a button, which when clicked (button), a modalpopup extender will open with values display in grid-view (values from database),
If the user select any row, the name of the selected person must display in the text box of the parent form as shown below;
I have written this code,
C# Code:
//GridView inside the Modal popup
protected void grdPersonDetails_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdPersonDetails.SelectedRow;
Session["testSession"] = row.Cells[0].Text;
ViewState["testViewState"] = row.Cells[0].Text;
ChargeFilterModalDialogExtender.Hide();
txtPersonName.Text = (string) ViewState["sometest"];
txtPersonName.Text = (string) Session["sometest"];
}
ASP Code:
<asp:Label ID="Label1" runat="Server" Text="Person Name:"></asp:Label>
<asp:TextBox runat="Server" ID="txtPersonName" />
<asp:Button runat="server" ID="btnSelectPerson" Text="Select Person" />
<ajax:ModalPopupExtender ID="ChargeFilterModalDialogExtender" runat="server" TargetControlID="btnSelectPerson" CancelControlID="BtnCloseChargeFilterControl" Drag="false" PopupControlID="Dialog_ChargeFilter" Enabled="True" BackgroundCssClass="modalBackground" />
<asp:Button ID="BtnShowDialog" Style="display: none" runat="server" Width="120" Text="Filter Charges" ToolTip="show Chargefilter-Dialog" />
<asp:Panel ID="Dialog_ChargeFilter" CssClass="modalPopup" runat="server">
<asp:Panel ID="DialogHeaderFrame" CssClass="DialogHeaderFrame" runat="server">
<asp:Panel ID="DialogHeader" runat="server" CssClass="DialogHeader" ScrollBars="Auto">
<asp:Label ID="LblPopupHeader" runat="server" Text="Charge-Filter" />
</asp:Panel>
</asp:Panel>
<asp:UpdatePanel ID="UpdGrdCharge" runat="server" UpdateMode="conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<asp:Button ClientIDMode="Static" ID="BtnCloseChargeFilterControl" Text="close filter" ToolTip="close filter-dialog" CausesValidation="false" Width="150px" runat="server" OnClick="BtnCloseChargeFilterControl_Click" /><br />
<table border="1">
<tr>
<td dir="rtl">
<asp:GridView ID="grdPersonDetails" runat="server" AutoGenerateColumns="False" DataKeyNames="PersonName,PersonEmail" DataSourceID="TempSqlDataSource" OnSelectedIndexChanged="grdPersonDetails_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="PersonName" HeaderText="Person Name" ReadOnly="True" SortExpression="PersonName" />
<asp:BoundField DataField="PersonEmail" HeaderText="Person Email" ReadOnly="True" SortExpression="PersonEmail" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CommandName="Select" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<asp:SqlDataSource ID="TempSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="select * from person.persons"></asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
The issue is that when I am selecting a person in the grid-view (inside the modal popup), the selected person name not appear in the related text box in the parent form. (when debugging it, it shows that the value of person name set in the text box)
Hi Abdul here is a complete demo - tested by me - working 100% successfully.
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="ModalPopupExtenderAJAXToolkitWebApp._Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<style type="text/css">
.searchButton
{
left: 319px;
position: absolute;
top: 145px;
width: 27px;
}
</style>
<link href="Styles/jquery.tooltip.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//Hiding Table Available inside div #dvDetails
// $('#dvDetails').hide();
/* Binding click event to each imagebutton inside GridView1
* which is taking value from current row and assigning
* to controls inside table
*/
$("#<%=GridView1.ClientID %> input[name*='imgbtn']").each(function (index) {
$("#<%=GridView1.ClientID %> input[name*='imgbtn']").bind('click', function (e) {
var id = $(this).closest('tr').find("span[id*='lblUserId']").text();
var username = $(this).closest('tr').find("input[name*='txtUserName']").val();
var firstname = $(this).closest('tr').find("input[name*='txtFirstName']").val();
var lastname = $(this).closest('tr').find("input[name*='txtLastName']").val();
var city = $(this).closest('tr').find("input[name*='txtCity']").val();
var designation = $(this).closest('tr').find("input[name*='txtDesignation']").val();
$('#<%=lblID.ClientID %>').text(id);
$('#<%=lblusername.ClientID %>').text(username);
$('#<%=txtfname.ClientID %>').val(firstname);
$('#<%=txtlname.ClientID %>').val(lastname);
$('#<%=txtCity.ClientID %>').val(city);
$('#<%=txtDesg.ClientID %>').val(designation);
});
});
/* Binding click event to each selected radiobutton inside GridView1
* which is taking value from current row and assigning
* to controls inside table
*/
$('input[value=Remove]').click(function () {
$('#dvDetails').show();
var id = $(this).closest('tr').find("span[id*='lblUserId']").text();
var username = $(this).closest('tr').find("input[name*='txtUserName']").val();
var firstname = $(this).closest('tr').find("input[name*='txtFirstName']").val();
var lastname = $(this).closest('tr').find("input[name*='txtLastName']").val();
var city = $(this).closest('tr').find("input[name*='txtCity']").val();
var designation = $(this).closest('tr').find("input[name*='txtDesignation']").val();
$('#<%=lblID.ClientID %>').text(id);
$('#<%=lblusername.ClientID %>').text(username);
$('#<%=txtfname.ClientID %>').val(firstname);
$('#<%=txtlname.ClientID %>').val(lastname);
$('#<%=txtCity.ClientID %>').val(city);
$('#<%=txtDesg.ClientID %>').val(designation);
});
var $fieldRevItems = $("#dvDetails");
$('#<%=btnClose2.ClientID %>').click(function (e) {
$('#<%=txtSearch.ClientID %>').val('');
// $fieldRevItems.hide('slow');
$fieldRevItems.slideUp(600);
e.preventDefault();
});
});
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<asp:ToolkitScriptManager ID="ScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div id="dvMain" style="height: 341px; width: 928px">
<div id="dvFirst">
Search user Details : <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:ImageButton ID="imgSearch" CssClass="searchButton" title="Search data for this id"
ImageUrl="~/search2.jpg" runat="server" OnClick="imgSearch_Click" />
<asp:Button ID="btnShowPopup2" runat="server" Style="display: none" />
<br />
<br />
<asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="btnShowPopup2"
PopupControlID="pnlpopup2" CancelControlID="btnClose" BackgroundCssClass="modalBackground">
</asp:ModalPopupExtender>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlpopup2" runat="server" BackColor="Green" Height="269px" Width="600px"
Style="display: none; top: 191px;width: 780px;">
<asp:GridView runat="server" ID="GridView1" DataKeyNames="UserId"
AutoGenerateColumns="false">
<rowstyle backcolor="#EFF3FB" />
<footerstyle backcolor="#507CD1" font-bold="True" forecolor="White" />
<pagerstyle backcolor="#2461BF" forecolor="White" horizontalalign="Center" />
<headerstyle backcolor="#507CD1" font-bold="True" forecolor="White" />
<alternatingrowstyle backcolor="White" />
<columns>
<asp:TemplateField HeaderText="UserId">
<ItemTemplate>
<asp:Label ID="lblUserId" style="width:100px;" runat="server" Text='<%# Eval("UserId") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblUserId" style="width:100px;" runat="server" Text='<%# Eval("UserId") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:TextBox ID="txtUserName" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("UserName")%>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUserName" CssClass="css2" runat="server"
Text='<%# Eval("UserName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:TextBox ID="txtFirstName" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("FirstName")%>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:TextBox ID="txtLastName" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("LastName")%>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("LastName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:TextBox ID="txtCity" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("City")%>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCity" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("City")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:TextBox ID="txtDesignation" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("Designation")%>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDesignation" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("Designation")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Close">
<ItemTemplate>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:RadioButton ID="rbSelectUserId" runat="server" Checked="false" value="Remove"
AutoPostBack="true" CausesValidation="false"
/>
<asp:ImageButton ID="imgbtn" ImageUrl="~/Edit.jpg" runat="server" Width="25" Height="25"/>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
<asp:Button ID="btnClose" runat="server" Text="Cancel" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<br />
</div>
<div id="dvDetails">
<table id="tblDetails" width="30%" style="border: Solid 3px #D55500; height: 100%"
cellpadding="0" cellspacing="0">
<tr style="background-color: #D55500">
<td colspan="2" style="height: 10%; color: White; font-weight: bold; font-size: larger"
align="center">
User Details
</td>
</tr>
<tr>
<td align="right">
UserId:
</td>
<td>
<asp:Label ID="lblID" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
UserName:
</td>
<td>
<asp:Label ID="lblusername" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
FirstName:
</td>
<td>
<asp:TextBox ID="txtfname" runat="server" />
</td>
</tr>
<tr>
<td align="right">
LastName:
</td>
<td>
<asp:TextBox ID="txtlname" runat="server" />
</td>
</tr>
<tr>
<td align="right">
City:
</td>
<td>
<asp:TextBox ID="txtCity" runat="server" />
</td>
</tr>
<tr>
<td align="right" style="width: 100%">
Designation:
</td>
<td>
<asp:TextBox ID="txtDesg" runat="server" />
</td>
</tr>
<tr>
<td align="center" style="width: 100%">
<asp:Button ID="btnClose2" runat="server" Text="Close" />
</td>
</tr>
</table>
</div>
</div>
</asp:Content>
//====================================================================================
and here is your code behind file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Configuration;
namespace ModalPopupExtenderAJAXToolkitWebApp
{
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
protected void BindGridData()
{
con.Open();
using (SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
UpdatePanel1.Update();
}
}
protected DataTable SearchDetails(string id)
{
DataTable dt = new DataTable();
con.Open();
using (SqlCommand cmd = new SqlCommand("Select * from Employee_Details where UserId=#UserId", con))
{
cmd.Parameters.Add(new SqlParameter("#UserId",Convert.ToInt32(id)));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
return dt;
}
protected void imgSearch_Click(object sender, EventArgs e)
{
string id = txtSearch.Text;
if (id != null)
{
DataTable dt = new DataTable();
dt = SearchDetails(id);
GridView1.DataSource = dt;
GridView1.DataBind();
UpdatePanel1.Update();
this.ModalPopupExtender2.Show();
}
}
}
}

Categories