create a filter row with textboxes on each column in asp.net gridview - asp.net

I have a asp.net gridview, which i am binding at runtime with a custom List object. I want to add a filter row below the header row on each column and on click of filter button grid data should get filtered based on values written in the filter textboxes. requirement seems weird but this is what client wants. please help with some clue.

aspx code :
<asp:TemplateField>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="150px" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="150px" />
<HeaderTemplate>
<table>
<tr>
<td align="center">
<asp:ImageButton runat="server" ID="imgFilter1" ImageUrl="../Images/filter.png" Style="height: 20px;
width: 20px;" OnClick="imgFilter1_click" />
</td>
<td align="center">
<asp:TextBox runat="server" ID="gridTextboxFilter1" AutoPostBack="true" onTextChanged="gridTextboxFilter1_text_changed">
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="center" colspan="2">
//your column header
</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("your_dataFeild") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
cs code :
private void BindGrid(string strFilter)
{
try
{
// Simple created a table to bind with Grid view and
// populated it with data.
DataTable dt = new DataTable("sample");
dt.Columns.Add("ID");
dt.Columns.Add("Name");
DataRow dr ;
for(int counter=1;counter<11;counter++)
{
dr = dt.NewRow();
dr["ID"]=counter.ToString();
dr["Name"]= "Cat" + counter.ToString();
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
if(strFilter != "")
dv.RowFilter="Name like '%" + strFilter + "%'";
if (CategoryFilter == "")
gvCategory.DataSource = dv;
else
gvCategory.DataSource = dv;
gvCategory.DataBind();
}
catch (Exception ex)
{
}
finally
{
}
}
protected void gridTextboxFilter1_text_changed(object sender, EventArgs e)
{
string text = ((TextBox)sender).Text;
BindGrid(text);
}

Add a textbox and button on the header template.
Write a query on button press and get the value.
The query something like select * from tbl where col like '%val%'
Bind the value to gridView.
I think this will solves for you

Related

ASP.NET Edit a Field without reloading the whole Listview

I have a Listview and a dropdownlist:
<asp:ListView ID="lv_ClassTeacher" runat="server" vertical-align="top" OnSelectedIndexChanged="lv_ClassTeacher_SelectedIndexChanged" OnSelectedIndexChanging="lv_ClassTeacher_SelectedIndexChanging" DataKeyNames ="ClassID" OnPagePropertiesChanged="lv_ClassTeacher_PagePropertiesChanged" OnPagePropertiesChanging="lv_ClassTeacher_PagePropertiesChanging" OnItemDataBound="lv_ClassTeacher_ItemDataBound" OnItemCommand="lv_ClassTeacher_ItemCommand">
<LayoutTemplate>
<table border="1">
<tr runat="server">
<th runat="server"></th>
<th runat="server">Class</th>
<th runat="server">Teacher</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:Button ID="cmd_View" runat="server" CommandName="Select" Text="View" Height="21px" /></td>
<td><div runat="server" id="area"><asp:Label ID="Label1" runat="server" Text='<%#Eval("Class") %>' /></div></td>
<td><asp:Label ID="Label2" runat="server" Text='<%#Eval("Teacher") %>' /></td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:DropDownList ID="cb_SwitchTeacher" runat="server" AutoPostBack = "true" OnSelectedIndexChanged="cb_SwitchTeacher_SelectedIndexChanged">
Part of code behind:
conn.Open();
using (MySqlCommand sqlCommand = conn.CreateCommand())
{
sqlCommand.CommandText = "SELECT * FROM tblClassTeacher";
using (MySqlDataAdapter sda = new MySqlDataAdapter(sqlCommand))
{
DataTable dt = new DataTable();
sda.Fill(dt);
lv_ClassTeacher.DataSource = dt;
lv_ClassTeacher.DataBind();
}
}
protected void cb_SwitchTeacher_SelectedIndexChanged(object sender, EventArgs e)
{
string TeacherName= cb_SwitchLabel.Text;
using (MySqlCommand sqlCommand = conn.CreateCommand())
{
sqlCommand.CommandText = "UPDATE tblClassTeacher SET Teacher=" + TeacherName + " WHERE ClassID=" + lv_ClassTeacher.SelectedDataKey.Value.ToString();
sqlCommand.ExecuteNonQuery();
//What can I do to update the listview without reloading the whole table?
}
}
}
On Pressing the "cmd_View", the Class field will be highlighted. When user switch to another Teacher on the dropdownlist, I will update the database.
But I want to update the listview as well without reloading the whole table.
Can I do that? Thank you.

DropDownList in ListView selectedValue always the first one

I have a ListView with DropDownList inside. I tried both: fill DropDownList on OnItemDataBound and in Page_Load. I also tried checking PostBack, but nothing helps.
When I try to get value, I always get the first one. I understand that it is because lists get refilled, but how to avoid it? If I fill them only when IsPostBack = false, they became empty.
This is my code:
<asp:ListView runat="server" ID="MyListView">
<LayoutTemplate>
<table border="0" cellpadding="2" cellspacing="0">
<tr>
<th><asp:Literal runat="server" Text='<%$ Resources: Resource, LabelWhole %>' /></th>
<th><asp:Literal runat="server" Text='<%$ Resources: Resource, LabelImport %>' /></th>
<th><asp:Literal runat="server" Text='<%$ Resources: Resource, LabelPeriod %>' /></th>
<th><asp:Literal runat="server" Text='<%$ Resources: Resource, LabelDate %>' /></th>
<th><asp:Literal runat="server" Text='<%$ Resources: Resource, LabelUpload %>' /></th>
</tr>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem, "Whole") %></td>
<td><%# DataBinder.Eval(Container.DataItem, "Upload")%></td>
<td><%# DataBinder.Eval(Container.DataItem, "Period")%></td>
<td><asp:DropDownList runat="server" ID="DaysDropDownList"></asp:DropDownList></td>
<td><asp:FileUpload ID="FileUpload" runat="server" /></td>
</tr>
</ItemTemplate>
</asp:ListView>
foreach (var lvItem in MyListView.Items)
{
if (lvItem.ItemType == ListViewItemType.DataItem)
{
DropDownList dr = lvItem.FindControl("DaysDropDownList") as DropDownList;
for (int i = -1; i >= -12; i--)
{
dr.Items.Add(new ListItem(
DateTime.Now.AddMonths(i).ToString("yyyy MM"),
DateTime.Now.AddMonths(i).ToString("yyyy MM")));
}
}
}
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
this.Application.DataLayer.LoadData(UserID);
this.MyListView.DataSource = this.Application.DataLayer.Data;
this.MyListView.DataBind();
LoadDropDownLists();
}
private void LoadDropDownLists()
{
foreach (var lvItem in MyListView.Items)
{
if (lvItem.ItemType == ListViewItemType.DataItem)
{
DropDownList dr = lvItem.FindControl("DaysDropDownList") as DropDownList;
dr.Items.Clear();
for (int i = -1; i >= -12; i--)
{
dr.Items.Add(new ListItem(
DateTime.Now.AddMonths(i).ToString("yyyy MM"),
DateTime.Now.AddMonths(i).ToString("yyyy MM")));
}
}
}
}
public void SubmitButtonClick(object sender, EventArgs e)
{
foreach (var lvItem in MyListView.Items)
{
if (lvItem.ItemType == ListViewItemType.DataItem)
{
DropDownList dr = lvItem.FindControl("DaysDropDownList") as DropDownList;
FileUpload fl = lvItem.FindControl("FileUpload") as FileUpload;
if (fl.HasFile)
{
string filename = UploadFile(fl, dr.SelectedValue);
this.Application.DataLayer.SaveUploadRecord(UserID, 0, (int)UploadType.Upload, dr.SelectedValue, filename);
}
}
}
}
When you populate your DropdownList with ListItem, you can set the ListItem's Selected property accordingly.
Create a function in which you bind the dropdownlist, Call this function everytime when the page loads(in the page_load event), but before calling it first clear the existing dropdownlist datasource.

asp.net datalist select all checkboxes per category

I have a page where users can select different documents files in a datalist control. The documents are categorized based on categories using the on pre-render event handler. Documents are selected based on Checkbox controls (not Checkboxlist). So far so good. What I want to happen next is to put a 'Select All' checkbox beside each Category's name which should select only checkboxes under that category. Here is the datalist control:
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Vertical" OnPreRender="DataList1_PreRender" DataKeyField="docid" EnableViewState="false">
<ItemTemplate>
<table cellpadding="0" cellspacing="0" id="tbl_data">
<tr>
<td>
<asp:Label ID="lblHeader" runat="server" Font-Bold="True" Font-Underline="True"></asp:Label>
<asp:Label runat="server" id="lbl_cb_all" visible="false">Select All <input runat="server" id="cb_selectall" type="checkbox" value='<%# Eval("catid") %>' /> </asp:Label>
</td>
</tr>
<tr runat="server" id="tr_data">
<td>
<asp:Label ID="lbl_categoryname" runat="server" Text='<%# Eval("categoryname") %>' Visible="false" /> <!-- Hide this; only used in Code Behind -->
<input runat="server" id="cb_docid" type="checkbox" value='<%# Eval("docid") %>' />
<asp:Hyperlink ID="hpl_docfileencr" Text='<%# Eval("docfileencr") %>' NavigateUrl='<%# "~/PDFEncr/" + DataBinder.Eval(Container.DataItem, "docfileencr") %>' Target="_blank" runat="server" />
<br />
</td>
</tr>
</table>
</ItemTemplate>
and here is the OnPreRender code:
protected void DataList1_PreRender(object sender, EventArgs e)
{
string strTempLabelCategory = "";
foreach (DataListItem item in DataList1.Items)
{
Label lbl_categoryname = item.FindControl("lbl_categoryname") as Label;
if (strTempLabelCategory.ToUpper() != lbl_categoryname.Text.ToString().ToUpper())
{
strTempLabelCategory = lbl_categoryname.Text.ToString().ToUpper();
Label lblHeader = item.FindControl("lblHeader") as Label;
lblHeader.Text = strTempLabelCategory.ToUpper();
Label lbltempdiv = item.FindControl("lbl_cb_all") as Label;
lbltempdiv.Visible = true;
}
}
}
I have looked for something which can work within my code but no luck. And I am too invested in this code to now try Checkboxlist control (not sure if that would help anyway).
Any ideas? I thought I could use: http://www.dotnetcurry.com/ShowArticle.aspx?ID=77 code but not sure how I can make that work? If I can somehow make the select all checkbox tie to a tag and then look for all tag then may be the link's code would help.
Thanks!
Use HiddenFields to store CatID and DocID
Use ASP.NET CheckBoxes instead of HTML-Inputs for both
Handle the Check-All Checkbox' CheckedChanged event:
protected void CheckAllChanged(Object sender, EventArgs e)
{
CheckBox checkAll = (CheckBox)sender;
DataListItem item = (DataListItem)checkAll.NamingContainer;
HiddenField HiddenCatID = (HiddenField)item.FindControl("HiddenCatID");
var catCheckBoxes = DataList1.Items.Cast<DataListItem>()
.Where(li => ((HiddenField)li.FindControl("HiddenCatID")).Value == HiddenCatID.Value)
.Select(li => li.FindControl("cb_docid"));
foreach (CheckBox docCheckBox in catCheckBoxes)
{
docCheckBox.Checked = checkAll.Checked;
}
}
on aspx:
<asp:CheckBox runat="server" OnCheckedChanged="CheckAllChanged" AutoPostBack="true" id="cb_selectall" />
<asp:HiddenField ID="HiddenCatID" runat="server" Value='<%# Eval("CatID") %>' />
<asp:HiddenField ID="HiddenDocID" runat="server" Value='<%# Eval("DocID") %>' />
You also need to EnableViewState=true on the DataList to maintain checkbox state and enable checking/unchecking.
Edit:
Because you have problems to get it running, here's a complete working sample page.
Here are the required controls on aspx(note f.e. <tr runat="server" id="tr_category">):
<ItemTemplate>
<table cellpadding="0" cellspacing="0" id="tbl_data">
<tr runat="server" id="tr_category">
<td>
<asp:Label ID="lblHeader" runat="server" Font-Bold="True" Text='<%# Eval("categoryname") %>' Font-Underline="True"></asp:Label>
<asp:Label runat="server" ID="lbl_cb_all">Select All
<asp:CheckBox runat="server" OnCheckedChanged="CheckAllChanged" AutoPostBack="true" id="cb_selectall" />
</asp:Label>
</td>
</tr>
<tr runat="server" id="tr_data">
<td>
<asp:HiddenField ID="HiddenCatID" runat="server" Value='<%# Eval("CatID") %>' />
<asp:CheckBox runat="server" id="cb_docid" />
<asp:HyperLink ID="hpl_docfileencr" Text='<%# Eval("docfileencr") %>' NavigateUrl='<%# "~/PDFEncr/" + DataBinder.Eval(Container.DataItem, "docfileencr") %>'
Target="_blank" runat="server" />
<br />
</td>
</tr>
</table>
</ItemTemplate>
Ensure that the DataList is databound only if(!IsPostback), otherwise the checkbox selection will not be maintained:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) BindDataList();
}
I'm using ItemDataBound instead of PreRender which is important for the ViewState to be reloaded correctly. I've also simplified all:
protected void DataList1_ItemDataBound(Object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
{
var row = (DataRowView)e.Item.DataItem;
var view = row.DataView;
var lastRow = e.Item.ItemIndex == 0 ? null : view[e.Item.ItemIndex-1];
var tr_category = (System.Web.UI.HtmlControls.HtmlTableRow)e.Item.FindControl("tr_category");
var sameCategory = lastRow != null && (int)row["catid"] == (int)lastRow["catid"];
tr_category.Visible = !sameCategory;
}
}
The CheckAllChanged remains unchanged.
This works as expected even if you select a single document-checkbox and select a category-checkbox afterwards which causes a postback.
I think I got this to work with slight modification of Tim's code. A few points: I had to disable ViewState for the datalist because, otherwise, the check-all trigger was not keeping boxes checked. I don't understand why. Also, there is not ispostback check in the page_load event and the datalist binds on every load. I am not that's 'optimal' or not. I have also made two sets of Asp:RadioButtons: CheckAll and CheckNone, instead of checkboxes. Anyway, here is the relevant code:
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Vertical" DataKeyField="docid"
EnableViewState="false" OnItemDataBound="DataList1_ItemDataBound">
<ItemTemplate>
<table cellpadding="0" cellspacing="0" id="tbl_data">
<tr runat="server" id="tr_category">
<td>
<asp:Label ID="lblHeader" runat="server" Font-Bold="True" Text='<%# Eval("categoryname") %>'
Font-Underline="True"></asp:Label>
<asp:Label runat="server" ID="lbl_cb_all">Select: All
<asp:RadioButton runat="server" OnCheckedChanged="CheckAllChanged" AutoPostBack="true"
ID="rb_selectall" GroupName="selectallnone" />
| None
<asp:RadioButton runat="server" OnCheckedChanged="CheckAllChangedNone" AutoPostBack="true"
ID="rb_selectnone" GroupName="selectallnone" />
<asp:HiddenField ID="HiddenCatID" runat="server" Value='<%# Eval("CatID") %>' />
<asp:HiddenField ID="HiddenDocID" runat="server" Value='<%# Eval("docid") %>' />
</asp:Label>
</td>
</tr>
<tr runat="server" id="tr_data">
<td>
<asp:CheckBox runat="server" ID="cb_docid" Value='<%# Eval("docid") %>' />
<asp:HyperLink ID="hpl_docfileencr" Text='<%# Eval("docfileencr") %>' NavigateUrl='<%# "~/PDFEncr/" + DataBinder.Eval(Container.DataItem, "docfileencr") %>'
Target="_blank" runat="server" />
<br />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
protected void DataList1_ItemDataBound(Object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var row = (DataRowView)e.Item.DataItem;
var view = row.DataView;
var lastRow = e.Item.ItemIndex == 0 ? null : view[e.Item.ItemIndex - 1];
var tr_category = (System.Web.UI.HtmlControls.HtmlTableRow)e.Item.FindControl("tr_category");
var sameCategory = lastRow != null && (int)row["catid"] == (int)lastRow["catid"];
tr_category.Visible = !sameCategory;
}
}
protected void CheckAllChanged(Object sender, EventArgs e)
{
RadioButton checkAll = (RadioButton)sender;
DataListItem item = (DataListItem)checkAll.NamingContainer;
HiddenField HiddenCatID = (HiddenField)item.FindControl("HiddenCatID");
var catCheckBoxes = DataList1.Items.Cast<DataListItem>()
.Where(li => ((HiddenField)li.FindControl("HiddenCatID")).Value == HiddenCatID.Value)
.Select(li => li.FindControl("cb_docid"))
.ToList();
foreach (CheckBox docCheckBox in catCheckBoxes)
{
// docCheckBox.Checked = checkAll.Checked;
docCheckBox.Checked = true;
}
}
protected void CheckAllChangedNone(Object sender, EventArgs e)
{
RadioButton checkAll = (RadioButton)sender;
DataListItem item = (DataListItem)checkAll.NamingContainer;
HiddenField HiddenCatID = (HiddenField)item.FindControl("HiddenCatID");
var catCheckBoxes = DataList1.Items.Cast<DataListItem>()
.Where(li => ((HiddenField)li.FindControl("HiddenCatID")).Value == HiddenCatID.Value)
.Select(li => li.FindControl("cb_docid"))
.ToList();
foreach (CheckBox docCheckBox in catCheckBoxes)
{
docCheckBox.Checked = false;
}
}
//partial code from the Order button follows; note the use of HiddenField
CheckBox cb = li.FindControl("cb_docid") as CheckBox;
if (cb != null)
{
if (cb.Checked)
{
HiddenField docid = li.FindControl("HiddenDocID") as HiddenField;
string dbcmd = #"Insert Into [order_details] (orderid,docid) Values (" + orderid + "," + docid.Value.ToString() + ")";
protected void chkAllN_CheckedChanged(object sender, EventArgs e)
{
lblSelectedRecord.InnerText = "0";
/*this Foreach Loop performing for find gridview*/
foreach (DataListItem dst in dstMulEmpSalInsert.Items)
{
GridView grd = (GridView)dst.FindControl("grdMulEmpSalInsert");
CheckBox chk_All = (CheckBox)grd.HeaderRow.FindControl("chkAllN");
if (chk_All.Checked == true)
{
/*this Foreach Loop performing for find gridview Controls*/
foreach (GridViewRow gvr in grd.Rows)
{
CheckBox chk_One = (CheckBox)gvr.FindControl("ChkSendOne");
chk_One.Checked = true;
txt_Salary.ReadOnly = false;
lblSelectedRecord.InnerText = (Convert.ToInt32(lblSelectedRecord.InnerText) + 1).ToString();
}
}
else
{
/*this Foreach Loop performing for find gridview Controls*/
foreach (GridViewRow gvr in grd.Rows)
{
CheckBox chk_One = (CheckBox)gvr.FindControl("ChkSendOne");
chk_One.Checked = false;
}
}
}
}

How to remember the selected checkboxes between each paging-press

I have a listview with paging. Every paging has 10 rows with with a username, an email and a checkbox.
I need to be able to check a couple of checkboxes, in different "pagings", press a button and send an email every to ever user that has been checked.
Trouble is I don't really know how to remember the selected checkboxes between each paging-press.
Are you with me?
Deos anyone have a similar solution or a few tips on how to do this?
I'd prefer to solv this without jQuery, but ordinare javascript or a C# solution works fine.
Thanks in advance!
Try this
http://forums.asp.net/t/1619741.aspx?Remember+checkboxes+in+ListView
you could maintain a List<> of selections (say ID to each record, unique value) and would have to persist that list in the ViewState. update the list on a page change. bind the checkbox checked property through a code-behind function that checks whether the id is in the list.
here's a sample:
<asp:ListView ID="ListView1" runat="server" OnPagePropertiesChanging="ListView1_PagePropertiesChanging">
<LayoutTemplate>
<table id="Table2" runat="server" class="listview" width="100%">
<tr>
<td>
<table id="itemPlaceholderContainer" runat="server">
<tr>
<th>
</th>
<th>
</th>
<th id="thid" runat="server" visible="false">
ID
</th>
<th id="thname" runat="server">
Name
</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr id="Tr3" runat="server">
<td id="Td2" runat="server" style="">
<asp:DataPager ID="DataPager1" runat="server" PageSize="5" PagedControlID="ListView1"
OnPreRender="DataPager1_PreRender">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<input type="checkbox" id="CheckBox1" runat="server" value='<%# Eval("ID") %>' checked='<%# Selected(Eval("ID")) %>' />
</td>
<td>
<asp:Label ID="lblID" runat="server" Text='<%# Eval("ID") %>' />
</td>
<td>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
code-behind:
List<string> cBoxSelections = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindListView();
}
}
private void BindListView()
{
ListView1.DataSource = CreateDataSource();
ListView1.DataBind();
}
protected DataTable CreateDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
for (int i = 0; i < 33; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = string.Concat("Name",i.ToString());
dt.Rows.Add(dr);
}
return dt;
}
protected Boolean Selected(object sender)
{
Boolean flag = false;
string ID = Convert.ToString(sender);
if (!string.IsNullOrEmpty(ID))
{
flag = cBoxSelections.Exists(item => item.Equals(ID));
}
return flag;
}
private void UpdateSelections()
{
if (ViewState["sel"] != null)
{
cBoxSelections = (List<string>)ViewState["sel"];
}
foreach (ListViewDataItem item in ListView1.Items)
{
HtmlInputCheckBox cbox = (HtmlInputCheckBox)item.FindControl("CheckBox1");
if (cbox != null)
{
string selectedItem = cBoxSelections.Find(key => key.Equals(cbox.Value));
if (selectedItem == null)
{
if (cbox.Checked.Equals(true))
{
cBoxSelections.Add(cbox.Value);
}
}
if (selectedItem != null)
{
if (cbox.Checked.Equals(false))
{
cBoxSelections.Remove(cbox.Value);
}
}
}
}
if (cBoxSelections.Count > 0)
{
ViewState["sel"] = cBoxSelections;
}
}
protected void DataPager1_PreRender(object sender, EventArgs e)
{
BindListView();
}
protected void ListView1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
UpdateSelections();
}
you need the routines Selected (that returns a boolean) and UpdateSelections (which maintains), the rest of the code simply gets the ListView to demonstrate the sample along with dummy data.

ListView fields not getting posted

I know I've done something like this before, but I have no idea why it isn't working now. I have a ListView with some textboxes. I want to read the text out of those boxes when I click a button (linkbutton, whatever).
<asp:ListView runat="server" ID="lv_bar" EnableViewState="true">
<LayoutTemplate>
<table>
<tr>
<th>Foo</th>
</tr>
<tr runat="server" id="itemPlaceholder"></tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:LinkButton ID="lb_delete" CausesValidation="false" runat="server" Text="Del" /></td>
<td><asp:TextBox id="txt_foo" runat="server" /></td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:LinkButton ID="lb_add" CausesValidation="false" runat="server" Text="Add" />
And then here's the relevant code-behind stuff:
protected void Page_Load(object sender, EventArgs e)
{
lb_chapter_add.Click += lb_chapter_add_Click;
if (!IsPostBack)
{
lv_chapters.DataSource = new List<Foo>() { new Foo() { Name = "harbl"} };
lv_chapters.DataBind();
}
}
void lb_add_Click(object sender, EventArgs e)
{
foreach (ListViewDataItem item in lv_bar.Items)
{
var txt_foo = (TextBox)item.FindControl("txt_foo");
Response.Write("foo: " + txt_foo.Text);
}
Response.Write("<br />the end");
Response.End();
}
But what I see when I enter some text into txt_foo and click lb_add is just "the end". What am I doing wrong here?
The problem it that you are using a a non persistent object as DataSource.
Due to clicking the button, you generate a postback and lv_chapters does not contain any items. Set a breakpoint in the line where the foreach is and you will see that lv_chapters.Items in null, or that it's Count property returns 0.

Resources