I have a listboxitems i want that when i select value then page redirect to other page.I use onSelectedIndex property event function but it's not working.I search on google alot i find many solutions like autopostback property='true'. I apply all solutions but still not working.My listbox values coming from database and it load fine but page not redirecting to other page.
Here is my code aspx code:
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<div class="select-db">
<form runat="server"></form>
<label style="position:relative; font-weight:bold;bottom:230px; left:450px; color:White;">Select Database</label>
<asp:ListBox ID="ListBox1" runat="server" Height="202px" Width="262px"
style="margin-left: 247px; margin-top: 68px"
onselectedindexchanged="ListBox_Changed" AutoPostBack="true" EnableViewState="True" >
</asp:ListBox>
</div>
</asp:Content>
and here is my aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
getdata();
}
}
public void getdata()
{
string user = Session["name"].ToString();
SqlConnection cnn = new SqlConnection("Data Source=HAMEED_KHAN\\SQLEXPRESS;Initial Catalog=db_compiler;Integrated Security=True");
SqlCommand cmd2 = new SqlCommand("SELECT User_ID from tbl_user WHERE User_Name='" + user + "'", cnn);
cnn.Open();
string id = cmd2.ExecuteScalar().ToString();
int ID = Int32.Parse(id);
SqlCommand cmd = new SqlCommand("USE db_compiler SELECT Database_Name FROM Create_db WHERE User_ID='" + ID + "'", cnn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
string value = row["Database_Name"] + "";
ListBox1.Items.Add(value);
}
}
}
public void ListBox_Changed(object sender, EventArgs e)
{
Session["value"] = ListBox1.SelectedValue;
Response.Redirect("CreateTable.aspx");
}
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
}
I also use 'breakpoint' to check that event is firing or not but event is not firing.I don't know why?????
All asp.net controls have to be inside a <form> that has a runat="server" attribute. Move the closing tag of your form to the end of the content and it should work. Like this:
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<div class="select-db">
<form runat="server">
<label style="position:relative; font-weight:bold;bottom:230px; left:450px; color:White;">Select Database</label>
<asp:ListBox ID="ListBox1" runat="server" Height="202px" Width="262px" style="margin-left: 247px; margin-top: 68px" OnSelectedIndexChanged="ListBox_Changed" AutoPostBack="true" EnableViewState="True" >
</asp:ListBox>
</form>
</div>
</asp:Content>
Also remember you can only have one <form> with runat="server".
Related
I'm building an ASP.NET web application. I have an .ASPX page where I created a static GridView that I fill (with a SQL Server stored procedure) after the click of a button. I need to implement paging, but it doesn't work: when I click on page 2, 3 or whatever, the GridView seems to disappear.
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="UDC.aspx.cs" Inherits="DynamicStoreWebApplication.UDC" %>
<link href="Controls.css" rel="stylesheet" type="text/css" />
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>DynamicStore Web - Unità di carico</title>
</head>
<body>
<form id="form1" runat="server">
<div runat="server">
<asp:PlaceHolder ID="PlaceHolderHeader" runat="server"></asp:PlaceHolder>
<div style="float: left; width: 10%; background: #fff2e6;">
<asp:PlaceHolder ID="PlaceHolderMenu" runat="server"></asp:PlaceHolder>
</div>
<div style="padding: 25px; padding-left: 200px; width: 90%;">
<asp:Label ID="DateFromLbl" runat="server" Text="Dal giorno: " CssClass="label"></asp:Label>
<asp:TextBox ID="DateFrom" runat="server" Width="130px" TextMode="Date" CssClass="dropdown" Font-Names="Tahoma">2000-01-01</asp:TextBox>
<asp:Label ID="DateToLbl" runat="server" Text="Al giorno: " CssClass="label"></asp:Label>
<asp:TextBox ID="DateTo" runat="server" Width="130px" TextMode="Date" CssClass="dropdown" Font-Names="Tahoma"></asp:TextBox>
<asp:Label ID="Ricerca" runat="server" Text="Ricerca: " CssClass="label"></asp:Label>
<asp:TextBox ID="Search" runat="server" Width="95px" TextMode="SingleLine"></asp:TextBox>
<asp:Label ID="Risultati" runat="server" Text="Ultimi risultati: " CssClass="label"></asp:Label>
<asp:CheckBox ID="TopResults" runat="server" EnableViewState="true" ViewStateMode="Enabled"/>
<asp:Button ID="btnSubmit" runat="server" Text="Visualizza UDC" CssClass="control-button" OnClick="btnSubmit_Click"/>
<br />
<br />
<div style = "overflow-x:auto; width:100%">
<asp:GridView ID="GridView1" runat="server" CssClass="mydatagrid" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header"
RowStyle-CssClass="rows" EnableSortingAndPagingCallbacks="True" AutoGenerateEditButton="False" ShowHeaderWhenEmpty="True"
EnableViewState="true" AllowPaging="True" PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging">
</asp:GridView>
</div>
</div>
<asp:PlaceHolder ID="PlaceHolderFooter" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
ASPX.CS (code behind)
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
namespace DynamicStoreWebApplication
{
public partial class UDC : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UserControl uc1 = (UserControl)Page.LoadControl("~/Header.ascx");
PlaceHolderHeader.Controls.Add(uc1);
UserControl uc2 = (UserControl)Page.LoadControl("~/Menu.ascx");
PlaceHolderMenu.Controls.Add(uc2);
UserControl uc3 = (UserControl)Page.LoadControl("~/Footer.ascx");
PlaceHolderFooter.Controls.Add(uc3);
DateTo.Text = DateTime.Today.ToString("yyyy-MM-dd");
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
BindGridView();
}
protected void BindGridView()
{
string conn = "";
conn = ConfigurationManager.ConnectionStrings["Connection"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
try
{
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("DY_FindUdcList", objsqlconn);
objcmd.CommandType = CommandType.StoredProcedure;
SqlParameter RCp = objcmd.Parameters.Add("#RC", SqlDbType.Int);
RCp.Direction = ParameterDirection.ReturnValue;
SqlParameter DateFromp = objcmd.Parameters.Add("#DateFrom", SqlDbType.DateTime);
DateFromp.Value = DateFrom.Text;
SqlParameter DateTop = objcmd.Parameters.Add("#DateTo", SqlDbType.DateTime);
DateTop.Value = DateTo.Text;
SqlParameter UdcCelp = objcmd.Parameters.Add("#UdcCel", SqlDbType.Int);
UdcCelp.Value = -1;
SqlParameter TopResultsp = objcmd.Parameters.Add("#TopResults", SqlDbType.Bit);
if (TopResults.Checked)
{
TopResultsp.Value = 1;
}
else
{
TopResultsp.Value = 0;
}
SqlParameter Searchp = objcmd.Parameters.Add("#Search", SqlDbType.VarChar);
Searchp.Value = Search.Text;
SqlParameter Operp = objcmd.Parameters.Add("#Oper", SqlDbType.VarChar);
Operp.Value = "";
SqlParameter Termp = objcmd.Parameters.Add("#Term", SqlDbType.VarChar);
Termp.Value = "";
SqlParameter Errorep = objcmd.Parameters.Add("#Errore", SqlDbType.VarChar);
Errorep.Value = "";
Errorep.Direction = ParameterDirection.Output;
SqlDataAdapter adapter = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
objcmd.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
finally
{
objsqlconn.Close();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView();
}
}
}
Your code should work but remove EnableSortingAndPagingCallbacks="True" from the gridview declaration and try it. I think you have not also allowed sorting..
hi i tried to display image from sql table to gridview but its not displaying this is my code to bind gridview with sql table records.....
When the user login , the user login photo should display thats y i am trying
the image already stored in database but there is an ISSUE to retrive the image from database to gridview
PostBookChat.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblsession.Text = "Welcome" + Convert.ToString(Session["UName"]);
sessionimage();
}
}
private void sessionimage()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
try
{
int EmpID = (int)Session["EmpID"];
SqlDataAdapter Adp = new SqlDataAdapter("select EmpID,Photo from TBL_PBLogin where EmpID='" + EmpID + "'", con);
DataTable Dt = new DataTable();
con.Open();
Adp.Fill(Dt);
gridviewphoto.DataSource = Dt;
gridviewphoto.DataBind();
con.Close();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
PostBookChat.aspx
<body>
<form id="form1" runat="server">
<div>
<div id="header">
<img src="Image/book.png" height="60" width="140" style ="margin-left:0px;float:left;"/>
<div id="login">
<b><asp:Label ID="lblsession" runat="server" ForeColor="white" CssClass="label"></asp:Label>
<asp:GridView ID="gridviewphoto" runat="server" AutoGenerateColumns="false" BackColor="#CC3300" ForeColor="Black" ShowHeader="false" GridLines="None">
<Columns>
<asp:TemplateField ControlStyle-Width="100" ControlStyle-Height="100">
<ItemTemplate>
<asp:Image ID="Image" runat="server" ImageUrl='<%# "~/Handler.ashx?id=" + Eval("EmpID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnlogout" runat="server" Text="Sign Out" CssClass="myButton" OnClick="btnlogout_Click"/>
</div>
</div>
</body>
Handler.ashx
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["EmpID"] == null) return;
string connStr = ConfigurationManager.AppSettings["connect"].ToString();
string pictureId = context.Request.QueryString["EmpID"];
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Photo FROm TBL_PBLogin WHERE EmpID = #EmpId", conn))
{
cmd.Parameters.Add(new SqlParameter("#EmpID", pictureId));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.ContentType = "image/png";
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("Photo")]);
reader.Close();
}
}
}
}
DataBase
EmpID (PK,int notnull) (1,1)
UName(varchar(255),notnull)
Password(varchar(255),notnull)
Photo(image,null)
I am making an application about article publication. I have 2 tables
"artikulli"
id int Unchecked
tema varchar(250) Checked
abstrakti text
data_publikimit date
path varchar(350)
keywords varchar(350)
kategoria_id int
departamenti_id int
"kategorite"
id int Unchecked
emertimi varchar(350)
I want to display in a dropdown list all values of field "emertimi" and when the user selects one value to save id of that value in table "artikulli".
I have done the following, but I have the problem with syntax because I am using DATALIST.
public partial class AddArticle : System.Web.UI.Page
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
try
{
if (!IsPostBack)
{
Bind();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
public void Bind()
{
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
protected void datalist2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
TextBox txtAbstrakti = e.Item.FindControl("txtAbstrakti") as TextBox;
TextBox txtData = e.Item.FindControl("txtData") as TextBox;
TextBox txtKeywords = e.Item.FindControl("txtKeywords") as TextBox;
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection conn = new SqlConnection(connection);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "Insert into artikulli(tema,abstrakti,data_publikimit,path,keywords,kategoria_id) values (#tema,#abstrakti,#data,#filename,#keywords,#kategoria)";
command.Parameters.Add(new SqlParameter("#tema", txtTema.Text));
command.Parameters.Add(new SqlParameter("#abstrakti", txtAbstrakti.Text));
command.Parameters.Add(new SqlParameter("#data", txtData.Text));
command.Parameters.Add(new SqlParameter("#keywords", txtKeywords.Text));
command.Parameters.Add(new SqlParameter("#kategoria", drpdKategoria.SelectedValue));
FileUpload FileUploadArtikull = (FileUpload)e.Item.FindControl("FileUploadArtikull");
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise se file qe lejohet eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
//add parameters
command.Parameters.AddWithValue("#filename", filename);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni ngarkuar asnje artikull');", true);
}
}
}
AddArtikull.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddArtikull.aspx.cs" Inherits="AddArticle" MasterPageFile="~/MasterPage2.master" %>
<asp:Content ID="content2" ContentPlaceholderID=ContentPlaceHolder2 runat="server">
<asp:DataList ID="datalist2" runat="server"
onitemcommand="datalist2_ItemCommand" >
<FooterTemplate>
<section id="main" class="column" runat="server" style="width:900px;">
<article class="module width_full" style="width:900px;">
<header><h3 style="text-align: center">Shto Artikull </h3></header>
<div id="Div1" class="module_content" runat="server">
<asp:Label ID="Label1" runat="server" style="font-weight: 700">Tema</asp:Label>
<fieldset>
<asp:TextBox ID="txtTema" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTema" runat="server"
ControlToValidate="txtTema" Display="Dynamic"
ErrorMessage="Kjo fushe eshte e nevojshme" style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset><br />
<asp:Label ID="Label6" runat="server" style="font-weight: 700">Abstrakti</asp:Label>
<fieldset>
<asp:TextBox ID="txtAbstrakti" style="height:250px;" Textmode="Multiline" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorAbstrakti" runat="server"
ControlToValidate="txtAbstrakti" ErrorMessage="Kjo fushe eshte e nevojshme"
style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset>
<asp:Label ID="lblData" runat="server" style="font-weight: 700">Data e Publikimit</asp:Label>
<fieldset>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox>
</fieldset>
<asp:Label ID="lblKeywords" runat="server" style="font-weight: 700">Keywords</asp:Label>
<fieldset>
<asp:TextBox ID="txtKeywords" runat="server"></asp:TextBox>
</fieldset>
<br />
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<div>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Insert"
/>
</div><br />
<strong>Ngarko Artikull</strong><br />
<asp:FileUpload ID="FileUploadArtikull" runat="server" /><br />
<br />
<asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />
</div>
</article>
</section>
</FooterTemplate>
</asp:DataList>
</asp:Content>
It shows this error:
Compiler Error Message: CS0103: The name 'e' does not exist in the
current context
In this line:
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
In your bind method you are calling an object e that doesn't exist. If the dropdownlist isn't inside a bound element, you can just reference the front code directly, e.g.
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
without finding the control as long as it is runat="server"
UPDATE
Okay, so you need to add an OnItemCreated event in your datalist
OnItemCreated="datalist2_OnItemCreated"
Then in that method you need this
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
That will work for if you only have the footer, if you add an itemtemplate then you just need to get rid of the check for the footer and on each item creation grab that dropdownlist for that item
I want partial postback(asyncpostback) instead fullpostback.but it's not working. Dynamically created checkbox where check or unchecked checkbox cause fullpostback
but it should be asyncpostback.Here is my code.....
<asp:CheckBoxList ID="chkList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="chkList_SelectedIndexChanged"
ClientIDMode="AutoID">
</asp:CheckBoxList>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblMessage" runat="server" Visible="false"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="chkList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
C# code:
private static readonly string constring = ConfigurationManager.ConnectionStrings["ConnectionStrRead"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(constring);
SqlCommand com = new SqlCommand("Select * from Category");
com.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
int dtRows = dt.Rows.Count;
List<string> itemList = new List<string>();
for (int i = 0; i < dtRows; i++)
{
//itemList = new List<string>();
string item = dt.Rows[i]["CategoryName"].ToString() + "(" + dt.Rows[i]["CreateUser"].ToString() + ")";
itemList.Add(item);
}
chkList.DataSource = itemList.ToArray();
chkList.DataBind();
con.Close();
}
}
protected void chkList_SelectedIndexChanged(object sender, EventArgs e)
{
lblMessage.Visible = true;
lblMessage.Text = string.Empty;
foreach (ListItem item in chkList.Items)
{
if (item.Selected)
{
lblMessage.Text += item.Text + "<br/>";
}
}
}
Can u check your scriptmanager EnablePartialRendering attribute. It must be EnablePartialRendering="true"
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableViewState="False" EnablePartialRendering="true" EnableScriptGlobalization="true" > </asp:ScriptManager>
If problem is not about that u can try add AsyncPostBackTrigger in code behind
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(chkList);
I have a ListView and DropDownList in every Row of that ListView. You can cahnge a assigned person in that DropDownlist (the DropDownList shows Data from a MySql Database).
When changing the person I need to do some database operation. For that I need to know on which ListView Row the person was changed and I need to know the value of the entry.
Here is my aspx-file:
<asp:ListView ID="manageAssigneesListView" runat="server" DataKeyNames="" OnItemDataBound="OnDataBound">
<ItemTemplate>
<div class="summaryRow">
<asp:Label ID="customerId" runat="server"><%# Eval("customerId") %> </asp:Label>
<div style="width:200px; margin: 0px 5px; float: left;"><%# Eval("lastName") %>, <%# Eval("firstName") %></div>
<div style="width:120px; margin: 0px 2px; float: left;">Nr.</div>
<div style="width:200px; margin-left: 50px; float: right;">
<asp:DropDownList runat="server" ID="selectAssignee" Width="196" AppendDataBoundItems="true" OnSelectedIndexChanged="selectAssignee_OnSelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</div>
<div class="clear"></div>
</div>
</ItemTemplate>
</asp:ListView>
Here is my codebehind:
protected void Page_Load(object sender, EventArgs e)
{
Helper.doAuth(Session, Response);
if (!IsPostBack)
{
// load all customers without assignee
MySqlCommand cmd = new MySqlCommand();
MySqlConnection con = new MySqlConnection();
con.ConnectionString = Helper.CONNECTION_STRING;
cmd.CommandText = "SELECT customerId, lastName, firstName, assignee FROM customer WHERE assignee IS NULL ORDER BY customerId DESC";
cmd.Connection = con;
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
manageAssigneesListView.DataSource = ds;
manageAssigneesListView.DataBind();
con.Close();
}
}
protected void OnDataBound(object sender, ListViewItemEventArgs e)
{
DropDownList selectAssignee = (e.Item.FindControl("selectAssignee") as DropDownList);
MySqlCommand cmd = new MySqlCommand();
MySqlConnection con = new MySqlConnection();
con.ConnectionString = Helper.CONNECTION_STRING;
cmd.CommandText = "SELECT * FROM user where role = " + Helper.ROLE_SALESPERSON;
cmd.Connection = con;
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
selectAssignee.DataSource = ds;
selectAssignee.DataTextField = "emailAdress";
selectAssignee.DataBind();
con.Close();
}
protected void selectAssignee_OnSelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropDownList = (DropDownList)sender;
ListViewItem listView = (ListViewItem)dropDownList.NamingContainer;
var test = listView.DataItem;
string test2 = listView.FindControl("customerId").ToString();
int rowIndex = (int)listView.DataItemIndex;
Label lblMessage = (Label)listView.FindControl("customerId");
}
I was successful getting the DataItemIndex of the Row I changed the value of the DropDownList, also the DropDownlist is firing correcty onSelectedIndexChanged, but what I need is the value of the Label "customerId" and I don't know how to get this value.
Thanks in advance
You need to use FindControl to get the reference to the Label, then use it's Text property:
ListViewItem item = (ListViewItem)dropDownList.NamingContainer;
Label lbltCustomerID = (Label) item.FindControl("customerId");
string customerID = lblCustomerID.Text;
By the way, the ListViewItem.DataItem is always null on postbacks.
Edit:
You should set the Text of the label, so instead of
<asp:Label ID="customerId" runat="server">
<%# Eval("customerId") %>
</asp:Label>
this
<asp:Label ID="customerId" runat="server"
Text='<%# Eval("customerId") %>' >
</asp:Label>
try to get the value of the label directly from the ListView like
DropDownList dropDownList = (DropDownList)sender;
ListViewItem listView = (ListViewItem)dropDownList.NamingContainer;
var test = listView.DataItem;
string test2 = listView.FindControl("customerId").ToString();
int rowIndex = (int)listView.DataItemIndex;
Label label = (Label)manageAssigneesListView.Items[rowIndex ].Controls[0];
or
Label label = (Label)manageAssigneesListView.Items[rowIndex].FindControl("customerId");
and make sure that the ListView doesn't bind everytime on postback
like if the ListView loaded on PageLoad don't forget to add it in :
if (!IsPostBack)
{
//Load ListView
}
Even if it's answered my solution worked great for me:
protected void myDdl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropDownList = (DropDownList)sender;
ListViewDataItem listView = (ListViewDataItem)dropDownList.NamingContainer;
int rowIndex = listView.DataItemIndex;
//Some logic
}
Not that i use ListViewDataItem instread of Peasmaker's solution