I have a DataList and bind it corrertly.
SqlCommand cmd = new SqlCommand(str_cmd, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dtlst_periodicTask.DataSource = ds;
dtlst_periodicTask.DataBind();
pds.DataSource = ds.Tables[0].DefaultView;
pds.AllowPaging = true;
pds.PageSize = 25;
pds.CurrentPageIndex = CurrentPage;
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
and some codes for paging.
After that, I need to add a number of Buttons in each row dynamically because the number of buttons is not fix.
foreach (DataListItem item in dtlst.Items)
{
Button btn = new Button();
btn.Click += new EventHandler(btn_Click);
pnl_users.Controls.Add(btn);
}
But the button click event does not work.
protected void btn_Click(object sender, EventArgs e)
{
// code does not fire.
}
When I put a Button in .aspx page, have access and it works.
protected void dtlst object source, DataListCommandEventArgs e)
{
}
but why are you attempting to inject a button?
Why not just include the button in the markup in the first place? I can't really see the need or reason to layout a datalist, and THEN decide to use code?
Just drag + drop in a button into the datalist, and you are quite much done.
So here is our datalist - we dropped in a plane jane button.
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" >
<ItemTemplate>
<div style="border-style:solid;color:black;width:300px;margin-left:25px">
<div id="mybox" runat="server" style="padding:5px;text-align:right">
<p>Hotel Name: <asp:TextBox ID="HotelName" runat="server" Text ='<%# Eval("HotelName") %>' /></p>
<p>First Name: <asp:TextBox ID="FirstName" runat="server" Text ='<%# Eval("FirstName") %>' /></p>
<p>Last Name: <asp:TextBox ID="LastName" runat="server" Text ='<%# Eval("LastName") %>' /></p>
<p>City: <asp:TextBox ID="City" runat="server" Text ='<%# Eval("City") %>' /></p>
<p>Province: <asp:TextBox ID="Province" runat="server" Text ='<%# Eval("Province") %>' /></p>
Active: <asp:CheckBox ID="Active" runat="server" Checked = '<%# Eval("Active") %>'/>
<br />
<asp:Button ID="cmdRow" runat="server" Text="Row click This item"
/>
</div>
</div>
<div style="height:15px"></div>
</ItemTemplate>
</asp:DataList>
And our code to fill looks like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
MyLoadData();
}
void MyLoadData()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT TOP 3 * FROM tblHotels ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, con))
{
con.Open();
DataList1.DataSource = cmdSQL.ExecuteReader();
DataList1.DataBind();
}
}
And we now have this:
Now, lets wire up the button click, like this:
so, create new event in above (inteli-sense offers this choice).
protected void cmdRow_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
DataListItem gRow = (DataListItem)btn.Parent;
Debug.Print("Row index = " + gRow.ItemIndex.ToString());
int pkID = (int)(DataList1.DataKeys[gRow.ItemIndex]);
Debug.Print("Data base PK id = " + pkID.ToString());
Debug.Print("Hotel name = " + ((TextBox)(gRow.FindControl("HotelName"))).Text);
Debug.Print("City = " + ((TextBox)(gRow.FindControl("City"))).Text);
Debug.Print("--------------------");
}
And out output is this:
Row index = 1
Data base PK id = 72
Hotel name = Banff Rocky Mountain Resort
City = Banff
--------------------
so, it not at all clear why you want to spend the time, effort, and that of writing code when you can as a general rule just drop in a good old plane jane button from the designer right into the datalist, and then simple wire up a event.
Edit:
You can lead a horse to water - but can you get the horse to drink the water?
You can as noted inject a button, but I REALLY but REALLY but REALLY do not recommend doing this.
However, to get the button click event to work, then you can do this:
HtmlButton btn = new HtmlButton();
btn.InnerText = "Index " + e.Item.ItemIndex;
btn.Attributes.Add("onclick","__doPostBack('BtnTest2','')");
btn.ViewStateMode = ViewStateMode.Enabled;
HtmlGenericControl MyDiv = (HtmlGenericControl)e.Item.FindControl("mybox");
MyDiv.Controls.Add(btn);
Edit2:
Ok, there seems to be a issue of persistence.
So, adding MUST occur on page load (or could be earlier).
And the buttons have to be re-inserted each time on post-backs.
This now works:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MyLoadData();
}
AddBtns();
}
void MyLoadData()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT TOP 3 * FROM tblHotels ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, con))
{
con.Open();
DataList1.DataSource = cmdSQL.ExecuteReader();
DataList1.DataBind();
}
}
}
void AddBtns()
{
foreach (DataListItem gRow in DataList1.Items)
{
Button btn = new Button();
btn.Text = "Index " + gRow.ItemIndex;
btn.ID = "Btn" + gRow.ItemIndex;
btn.Click += new EventHandler(BtnTest3);
HtmlGenericControl MyDiv = (HtmlGenericControl)gRow.FindControl("mybox");
MyDiv.Controls.Add(btn);
}
}
void BtnTest3(object sender, EventArgs e)
{
Debug.Print("buttn3 click");
}
Note two changes:
We don't add/inject the buttons ONLY on !IsPostback.
We inject the buttons each time on page load
We did not use the Item bound event.
Related
This is my code for displaying the gridview:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCart();
}
}
protected void LoadCart()
{
string _connStr = ConfigurationManager.ConnectionStrings["CartDB"].ConnectionString;
SqlConnection SQLConn = new SqlConnection(_connStr);
SqlDataAdapter SQLAdapter = new SqlDataAdapter("SELECT M.menuItemName, M.menuItemImage,totalQuantity, M.menuItemPrice * totalQuantity Total_Price" +
" FROM Cart C INNER JOIN itemSelected I ON C.username + C.itemSelectedID = I.username + I.itemSelectedID" +
" INNER JOIN menuItem M ON I.menuItemID + I.stallID = M.menuItemID + M.stallID", SQLConn);
DataTable DT = new DataTable();
SQLAdapter.Fill(DT);
CartGridView.DataSource = DT;
CartGridView.DataBind();
LoadPrice();
}
protected void LoadPrice()
{
string _connStr = ConfigurationManager.ConnectionStrings["CartDB"].ConnectionString;
SqlConnection SQLConn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand("SELECT SUM(M.menuItemPrice * totalQuantity)tabulatedPrice" +
" FROM Cart C INNER JOIN itemSelected I ON C.username + C.itemSelectedID = I.username + I.itemSelectedID" +
" INNER JOIN menuItem M ON I.menuItemID + I.stallID = M.menuItemID + M.stallID", SQLConn);
SQLConn.Open();
lbl_TotalPrice.Text = cmd.ExecuteScalar().ToString();
SQLConn.Close();
}
This is my code in attempting to retrieve a specific row, but it returns null.
protected void CartGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
int result = 0;
Cart cart = new Cart();
GridViewRow row = CartGridView.SelectedRow;
string itemName = row.Cells[0].Text;
if (e.CommandName == "minusQuantity")
{
int quantity = int.Parse(row.Cells[3].Text) - 1;
if (quantity > 0)
{
cart.CartUpdateQuantity(quantity, itemName);
}
else
{
result = cart.CartDelete(itemName);
}
}
else if (e.CommandName == "addQuantity")
{
int quantity = int.Parse(row.Cells[3].Text) + 1;
cart.CartUpdateQuantity(quantity, itemName);
}
Response.Redirect("UserShoppingCart.aspx");
}
And here is my aspx file:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h1>Cart<table class="nav-justified">
<tr>
<td style="width: 860px" class="modal-lg">Product</td>
<td style="width: 698px">Images</td>
<td class="modal-lg" style="width: 1265px">Quantity</td>
<td>
Price</td>
</tr>
<tr>
<td colspan="4">
<asp:GridView ID="CartGridView" runat="server" AutoGenerateColumns="False" Width="1514px" OnRowCommand="CartGridView_RowCommand" >
<Columns>
<asp:BoundField HeaderText="Product" ShowHeader="False" DataField="menuItemName" />
<asp:BoundField HeaderText="Images" ShowHeader="False" DataField="menuItemImage" />
<asp:ButtonField ButtonType="Button" CommandName="minusQuantity" Text="-" />
<asp:BoundField HeaderText="Quantity" DataField="totalQuantity" />
<asp:ButtonField ButtonType="Button" CommandName="addQuantity" Text="+" />
<asp:BoundField DataField="Total_Price" HeaderText="Price" ShowHeader="False" />
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td style="height: 39px; " colspan="3">Total:<asp:Label ID="lbl_TotalPrice" runat="server"></asp:Label>
</td>
<td style="height: 39px; width:50px;">
</td>
</tr>
</table>
</h1>
</asp:Content>
Could this issue arise from having an Sql Table as the datasource?
I have attempted,
string itemName = CartGridView.Rows[0].Cells[0].Text;
though it did work for the 1st row, I am uncertain on where to go next for the subsequent rows.
The selected index change does not fire untill after the row command.
Why not just drop in a plane jane regular button? That way you can style the button, and just have a regular and simple click event for the button.
So, change your markup button to this:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="cmdAddQty" runat="server" Text="+"
OnClick="cmdAddQty_Click" />
</ItemTemplate>
</asp:TemplateField>
So, just type in OnClick= (in the markup, and you be prompted for create new event). the result is a simple plain jane button click.
So, then the button click code can be:
protected void cmdAddQty_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
Debug.Print("Row index click = " + gRow.RowIndex);
int quantity = int.Parse(gRow.Cells[3].Text) + 1;
// cart.CartUpdateQuantity(quantity, itemName);
}
So, you can easy pick up the row as per above.
And if you going to type "over and over" some sql, then build a helper rotuine to save world poverty, say like this:
protected void LoadCart()
{
string strSQL =
#"SELECT M.menuItemName, M.menuItemImage,totalQuantity, M.menuItemPrice * totalQuantity Total_Price
FROM Cart C
INNER JOIN itemSelected I ON C.username + C.itemSelectedID = I.username + I.itemSelectedID
INNER JOIN menuItem M ON I.menuItemID + I.stallID = M.menuItemID + M.stallID";
CartGridView.DataSource = MyRst(strSQL);
CartGridView.DataBind();
LoadPrice();
}
protected void LoadPrice()
{
string strSQL =
#"SELECT SUM(M.menuItemPrice * totalQuantity)tabulatedPrice
FROM Cart C
INNER JOIN itemSelected I ON C.username + C.itemSelectedID = I.username + I.itemSelectedID
INNER JOIN menuItem M ON I.menuItemID + I.stallID = M.menuItemID + M.stallID";
lbl_TotalPrice.Text = MyRst(strSQL).Rows[0][0].ToString();
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
string strCon = ConfigurationManager.ConnectionStrings["CartDB"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strCon))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
Last but not least?
It is great to use and learn webforms. But, that is as long as you NOT paying for such a course, since webforms are now quite old, and while still rather popular? They are quite much now older and a legacy choice, one that been superseded by MVC and newer approaches.
So, I think WebForms are great, but NOT if you paying for books or a course in this day and age, and those peddling books and course(s) that teach webforms are really just using older outdated material, and thus taking a horrible advantage of un-suspecting students that don't know better.
Anyway, just drop in a plain jane regular button. You can dispense with row command and all that song and dance, as it not really required, and a simple regular button and button click event is easier anyway.
I have a datalist in my ASP.Net web form. The datalist has an image button and a hyperlink. These things are kept in the item template in the datalist. I want to get the id of the row in which the image is clicked. Here is my ASP.Net code
<div height="100%" width="100%" class="w3-center">
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand" OnSelectedIndexChanged="DataList1_SelectedIndexChanged1" >
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%#Eval("Image_path") %> ' CommandName="Item" CommandArguement='<%#Eval("Catg_Id") %>' Height="200" Width="350" NavigateUrl='<%#String.Concat("SelectedCatg.aspx?category=",Eval("Catg_Name")) %>'/><br />
<asp:HyperLink runat="server" NavigateUrl='<%#String.Concat("SelectedCatg.aspx?category=",Eval("Catg_Name")) %>' CssClass="link" Font-Size="18"><%#Eval("Catg_name") %></asp:HyperLink>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:DataList>
</div>
I have itemCommand event but it doesn't catch the event on clicking the image button.
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
String index=e.CommandArgument.ToString();
Response.Redirect("~/SelectedCatg.aspx?id=" + index);
/* if (e.CommandName.Equals("img"))
{
int AnswerId = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex].ToString());
}*/
}
Need help.
Thanks
This is how I bind my datalist
String conString = ConfigurationManager.ConnectionStrings["con"].ToString();
con = new SqlConnection(conString);
con.Open();
String query = "Select * from Category_Master";
cmd = new SqlCommand(query,con);
dr = cmd.ExecuteReader();
dt = new DataTable();
dt.Load(dr);
DataList1.DataSource = dt;
DataList1.DataBind();
did you try which command was fired? check this and let me know the result please.
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Item")
{
int index= Convert.ToInt32(e.CommandArgument);
Response.Redirect("~/SelectedCatg.aspx?id=" + index);
}
}
Hey I make one more question with my full code because I am really stuck in this point.
When page loads a panel is filled with Book Categories taken from a database. This Categories are linkbuttons too. When I click one category a table is created below with all books on that category.
In that table the first cell is filled with Book's Title that is Linkbutton too.
I just want when I click i that Book'S Title linkbutton to fire the book_Details functions
so that the page now will show only the book I chose.
Instead of that whenever I click books'title linkbutton page loads again from 0.
The markup is:
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<div style="position: relative; top: 5%; left: 5%;">
<asp:Panel ID="MyPanel" runat="server"></asp:Panel>
</div>
<asp:MultiView ID="MultiView2" runat="server">
<asp:View ID="View1" runat="server">
<div style="overflow: auto; height: 400px;">
<asp:Table ID="ProductTBL" runat="server" BorderColor="Black" BorderStyle="Double" CellPadding="5" CellSpacing="5" BorderWidth="1px">
</asp:Table>
</div>
</asp:View>
<asp:View ID="View2" runat="server">
<asp:Table ID="detail_TBL" runat="server" BorderColor="Black" BorderStyle="Double" CellPadding="5" CellSpacing="5" BorderWidth="1px"></asp:Table>
</asp:View>
</asp:MultiView>
</asp:Content>
And the code-behind is:
protected void Page_Load(object sender, EventArgs e)
{
String conString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" +
Server.MapPath("~/e-bookstoredb.accdb");
using (OleDbConnection connection = new OleDbConnection(conString))
{
connection.Open();
ыtring query = "SELECT * FROM category";
using (OleDbCommand cmd = new OleDbCommand(query, connection))
{
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string literal = (string)reader["Name"];
LinkButton lnk_button = new LinkButton();
lnk_button.Text = literal;
lnk_button.ID = "cat_B" + reader["ID"].ToString();
lnk_button.CommandArgument = reader["ID"].ToString();
lnk_button.CommandName = reader["ID"].ToString();
lnk_button.Command += new CommandEventHandler(books_Show);
MyPanel.Controls.Add(lnk_button);
MyPanel.Controls.Add(new LiteralControl("</br>"));
}
reader.Close();
}
connection.Close();
}
}
protected void books_Show(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
string cat = lnk.CommandArgument;
MultiView2.ActiveViewIndex = 0;
string ConStr = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" + Server.MapPath("~/e-bookstoredb.accdb");
using (OleDbConnection con = new OleDbConnection(ConStr))
{
con.Open();
string query = "SELECT * FROM product WHERE category = #cat";
using (OleDbCommand cmd = new OleDbCommand(query, con))
{
cmd.Parameters.AddWithValue("#cat", cat);
OleDbDataReader reader = cmd.ExecuteReader();
TableCell cell;
TableRow row = new TableRow();
TableCell titleCell = new TableCell();
titleCell.Text = "Τίτλος";
TableCell desCell = new TableCell();
desCell.Text = "Περιγραφή";
TableCell priceCell = new TableCell();
priceCell.Text = "Τιμή";
row.Cells.Add(titleCell);
row.Cells.Add(desCell);
row.Cells.Add(priceCell);
ProductTBL.Rows.Add(row);
LinkButton book_button;
while (reader.Read())
{
book_button = new LinkButton();
book_button.ID = "book" + reader["ID"].ToString();
book_button.Text = (string)reader["Title"];
book_button.CommandArgument = (string) reader["Title"];
book_button.CommandName = "cmd" + reader["ID"].ToString();
book_button.Command += new CommandEventHandler(book_Details);
row = new TableRow();
cell = new TableCell();
cell.Controls.Add(book_button);
row.Cells.Add(cell);
cell = new TableCell();
cell.Text = (string)reader["Description"];
row.Cells.Add(cell);
cell = new TableCell();
cell.Text = reader["price"].ToString()+"€";
row.Cells.Add(cell);
ProductTBL.Rows.Add(row);
}
reader.Close();
}
con.Close();
}
}
protected void book_Details(object sender, EventArgs e)
{
MultiView2.ActiveViewIndex = 1;
LinkButton lnk = sender as LinkButton;
String bookTitle = lnk.CommandArgument;
//...And then I just create a table to show only the book user selected
//...this table gets filled buy this query = " SELECT * FROM product WHERE Title=#bookTitle
}
You must wrap your code within Page_Load with if(!IsPostBack) as shown below. This is because according to ASP.Net page lifecycle Page_Load fires first and control events firs after that.
So, whenever you click your LinkButtons the server first calls the Page_Load and then it calls LinkButton's click event.
So, it's a good idea to wrap your Page_Load code where you only wants to execute once during Page_Load like this.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Your Page_Load logic goes here
}
}
According to MSDN the definition for IsPostBack is
Gets a value that indicates whether the page is being rendered for the
first time or is being loaded in response to a postback.
true if the page is being loaded in response to a client postback;
otherwise, false.
Hope this helped!
I have a gridview that is populated with data from SQL and I would like to add buttons/linkbuttons dynamically to its columns.
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
Button button = new Button();
button.ID = "row" + e.Row.RowIndex;
button.Text = "click me";
button.Click += new EventHandler(Unnamed_Click);
e.Row.Cells[1].Controls.Add(button);
}
Visually that works fine but when clicking it, it does a postback and the changes are lost. The buttons are gone.
Where can I recreate them so they persist?
You can use command field or template field for buttons,
below is example for image button:
<asp:CommandField ShowEditButton="true" EditImageUrl="~/images/edit.png" ButtonType="Image" ItemStyle-Width="20px" HeaderStyle-Width="20px" AccessibleHeaderText="Edit">
<HeaderStyle Width="20px" />
<ItemStyle Width="20px" />
</asp:CommandField>
Or
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" CommandName="Edit"
ImageUrl="~/images/edit.png" ToolTip="Click to Edit></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
Please use the below steps to bypass the binding of grid in case the click me button was clicked
Change your OnRowBound function code to:
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItemIndex != -1)
{
Button button = new Button();
button.ID = "gridview1row" + e.Row.RowIndex;
button.UseSubmitBehavior = false;
button.Text = "click me";
button.Click += new EventHandler(Unnamed_Click);
e.Row.Cells[1].Controls.Add(button);
}
}
Add the below check to you Page_Load before Grid View Load
protected void Page_Load(object sender, EventArgs e)
{
try
{
if ( Request.Params["__EventTarget"] == null || !Request.Params["__EventTarget"].Contains("gridview1row"))
{
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
using (SqlCommand command =
new SqlCommand("SELECT TOP 100 * FROM dbo.TableName", connection))
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = command;
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
}
catch (Exception ex)
{
}
}
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