ASP.NET Edit a Field without reloading the whole Listview - asp.net

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.

Related

How to display images by using listview in asp.net?

Iam using a listview to display table contents from mysql DB,thats working fine.But i want to know how to display images inside each column in listview table.
<LayoutTemplate>
<table runat="server" id="table1">
<tr id="Tr1" runat="server">
<th class="tablehead">
Movie Name
</th>
<th class="tablehead">
Movie Genre
</th>
<th class="tablehead">
Image
</th>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr id="Tr2" runat="server" class="tablerw">
<td style="background-color:#EEEEEE;width:100px;" class="tablerw"> <asp:Label ID="Label5" runat="server"
Text='<%#Eval("MovieName") %>' /></td>
<td style="background-color:#EEEEEE;width:100px;"> <asp:Label ID="NameLabel" runat="server"
Text='<%#Eval("movieGenre") %>' /></td>
<td style="background-color:#EEEEEE;width:100px;"> <asp:Label ID="Label1" runat="server"
Text='<%#Eval("Image") %>' /></td>
</tr>
</ItemTemplate>
Aspx.cs
public DataTable GetAllmoviedet()
{
DataTable dt1 = new DataTable();
try
{
string connString = cnst.cnstrin();
string query = "SELECT `moviemaster`.`MovieName`,`moviemaster`.`image`,`moviemaster`.`MovieGenre`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(dt1);
return dt1;
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var tbl = GetAllmoviedet();
ListView1.DataSource = tbl;
ListView1.DataBind();
GetAllmovie1();
}
}
By using these codes,i can manage to get image name only.So i need to display exact image instead of names.How can i possible this?any help?

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.

GridView isn't reflecting AJAX changes

I'm using AJAX right now to update my GridView when I search for a string of text in the gridview, or when I select from a dropdownlist what I want to order the Gridview by. This was working previously, but I had really messy code. So I've cleaned it up a little bit, added some parameters and such. Unfortunately, now, when the selectedindex of the dropdownlist is changed or when someone tries to search for a field, nothing happens - the page just refreshes. I'm also getting an exception saying "The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name".
If you need to see any more code then please let me know!
public vieworders()
{
this.PreInit += new EventHandler(vieworders_PreInit);
}
void vieworders_PreInit(object sender, EventArgs e)
{
orderByString = orderByList.SelectedItem.Value;
fieldString = searchTextBox.Text;
updateDatabase(fieldString, orderByString);
}
protected void updateDatabase(string _searchString, string _orderByString)
{
string updateCommand = "SELECT fName,lName,zip,email,cwaSource,price,length FROM SecureOrders WHERE fName LIKE #searchString OR lName LIKE #searchString OR zip LIKE #searchString OR email LIKE #searchString OR cwaSource LIKE #searchString OR length LIKE #searchString OR price LIKE #searchString ORDER BY #orderByString";
Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Cabot3");
ConnectionStringSettings connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["secureodb"];
// Create an SqlConnection to the database.
using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
using (SqlCommand _fillDatabase = new SqlCommand(updateCommand, connection))
{
connection.Open();
_fillDatabase.Parameters.Add("#searchString", SqlDbType.VarChar, 50).Value = _searchString;
_fillDatabase.Parameters.Add("#orderByString", SqlDbType.VarChar, 50).Value = _orderByString;
_fillDatabase.ExecuteNonQuery();
dataAdapter = new SqlDataAdapter("SELECT * FROM SecureOrders", connection);
// create the DataSet
dataSet = new DataSet();
// fill the DataSet using our DataAdapter
dataAdapter.Fill(dataSet, "SecureOrders");
DataView source = new DataView(dataSet.Tables[0]);
DefaultGrid.DataSource = source;
DefaultGrid.DataBind();
connection.Close();
}
}
Form
<form id="form1" runat="server">
<asp:ScriptManager ID = "ScriptManager" runat="server" />
<div>
<asp:Label runat="server" id = "orderByLabel" Text = "Order By: " />
<asp:DropDownList runat="server" ID="orderByList" AutoPostBack="true">
<asp:ListItem Value="fName" Selected="True">First Name</asp:ListItem>
<asp:ListItem Value="lName">Last Name</asp:ListItem>
<asp:ListItem Value="state">State</asp:ListItem>
<asp:ListItem Value="zip">Zip Code</asp:ListItem>
<asp:ListItem Value="cwaSource">Source</asp:ListItem>
<asp:ListItem Value="cwaJoined">Date Joined</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Label runat="server" ID="searchLabel" Text="Search For: " />
<asp:TextBox ID="searchTextBox" runat="server" Columns="30" />
<asp:Button ID="searchButton" runat="server" Text="Search" />
</div>
<div>
<asp:UpdatePanel ID = "up" runat="server">
<ContentTemplate>
<div style= "overflow:auto; height:50%; width:100%">
<asp:GridView ID="DefaultGrid" runat = "server" DataKeyNames = "IdentityColumn"
onselectedindexchanged = "DefaultGrid_SelectedIndexChanged"
autogenerateselectbutton = "true">
<SelectedRowStyle BackColor="Azure"
forecolor="Black"
font-bold="true" />
<Columns>
<asp:TemplateField HeaderText="Processed">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxProcess" AutoPostBack = "true" Checked ='<%#Eval("processed") %>' OnCheckedChanged="CheckBoxProcess_CheckedChanged" runat="server" Enabled="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
<div style= "overflow:auto; height:50%; width:100%" />
<table border="1">
<tr>
<td>Name: </td>
<td><%=name %></td>
</tr>
<tr>
<td>Zip: </td>
<td><%=zip %></td>
</tr>
<tr>
<td>Email: </td>
<td><%=email %></td>
</tr>
<tr>
<td>Length: </td>
<td><%=length %></td>
</tr>
<tr>
<td>Price: </td>
<td><%=price %></td>
</tr>
<tr>
<td>Source: </td>
<td><%=source %></td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
I have never used the UpdatePanel since my company uses Telerik, but from the examples I see during my research I remember seeing a trigger component.
From my understanding, if the control is w/i the UpdatePanel itself, then you do not have to specify the trigger, since it is assumed.
For your scenario, the trigger (dropdownlist) is outside of the UpdatePanel. You may need to include this in your aspx:
<asp:UpdatePanel ID = "up" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="orderByList" >
</Triggers>
<ContentTemplate>
...
Try the following:
In HTML move the update panel direct after the scriptmanager line.
Move the code lines in vieworders_PreInit to vieworders_PageLoad with !IsPostPack clause.

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

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

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.

Resources