Cannot Bind my Listview - asp.net

I want to bind my Listview but I can't. I dont know what I am doing wrong here. When I press ctrl+f5, the page is empty.
My Code is:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Student_ID">
<LayoutTemplate>
<table id="itemplaceholderContainer" runat="server">
<tr id="itemplaceholder">
<td>
Student ID :
</td>
<td>
Registration Number :
</td>
<td>
Student Name :
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
StudentID:
<asp:Label ID="LabelID" runat="server" Text='<%Eval("Student_ID") %>'></asp:Label>
StudentRegistrationNumber:<asp:Label ID="LabelNumber" runat="server" Text='<%Eval("StudentRegistrationNumber") %>'></asp:Label>
StudentName:<asp:Label ID="LabelName" runat="server" Text='<%Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:ListView>
</asp:Content>
Codebehind is :
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=LOCALHOST;Initial Catalog=ITCF;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Student", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.fill(dt);
ListView1.DataSource = dt;
ListView1.DataBind();
}

try this:
first your item template is worng, and also you need to fill the data adabter form the Data Table
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Student_ID">
<LayoutTemplate>
<table id="itemplaceholderContainer" runat="server">
<tr id="itemplaceholder">
<td>
Student ID :
</td>
<td>
Registration Number :
</td>
<td>
Student Name :
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
StudentID:
<asp:Label ID="LabelID" runat="server" Text='<%# Eval("Student_ID") %>'></asp:Label>
StudentRegistrationNumber:<asp:Label ID="LabelNumber" runat="server" Text='<%# Eval("StudentRegistrationNumber") %>'></asp:Label>
StudentName:<asp:Label ID="LabelName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:ListView>
</asp:Content>
Codebehind is :
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=LOCALHOST;Initial Catalog=ITCF;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Student", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ListView1.DataSource = dt;
ListView1.DataBind();
}

The last 3 lines of code in your code-behind tell the whole story:
DataTable dt = new DataTable();
ListView1.DataSource = dt;
ListView1.DataBind();
You're instantiating a new, empty DataTable and binding ListView1 to it. Thus, behaving correctly and exactly as designed, your ListView is displaying zero records from the empty DataTable.
You'll want to fetch the data from the DataAdapter before you bind anything to it. Something like this:
var students = new DataSet();
da.Fill(students, "Student");
if (students.Tables.Count == 1)
{
ListView1.DataSource = students.Tables[0];
ListView1.DataBind();
}
Note: There may be a more direct way to fetch the DataTable. I haven't worked with DataSets and DataTables in a long time, but .Fill() may be able to directly use a DataTable and skip my checking of a valid table in the DataSet above.)

Your datatable is never getting populated. Have a look at the following:
http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx

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.

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?

Take parameter from listview

i have this code:
protected void Button1_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(GetConnectionString());
{
System.Data.SqlClient.SqlCommand cmd;
sc.Open();
cmd = new System.Data.SqlClient.SqlCommand("SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;", sc);
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#ID", System.Data.SqlDbType.Text)).Value = (TextBox)ListView1.FindControl("box1");
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
I need take value ID from listview, but with this code I have this error:
...expects the parameter '#ID', which was not supplied....
This part of my listview...
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID_zapas" DataSourceID="SqlDataSource1" style="text-align: center ">
<AlternatingItemTemplate>
<tr style="background-color: #e9ffe9;color: #284775;text-align:center">
<td>
<asp:TextBox ID="box1" runat="server" Text='<%# Eval("ID_zapas") %>' Visible="false" />
...
<td style="width:50px;background-color:white">
<asp:LinkButton ID="Button1" runat="server" OnClick="Button1_Click" Visible='<%# HttpContext.Current.User.IsInRole("admin") %>' CausesValidation="False" OnClientClick="javascript: return confirm('Opravdu chcete zápas zkopírovat?');">
<asp:Image ID="Image2" runat="server" ImageUrl="~/Icons/copy.png" Width="29px" Height="29px" ToolTip="Zkopírovat zápas" />
</asp:LinkButton>
</td>
</tr>
</AlternatingItemTemplate>
Have you some idea?
As per comments, please try this:
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
var box1 = (TextBox)((LinkButton)sender).Parent.FindControl("box1");
using (var sc = new SqlConnection(GetConnectionString()))
{
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;";
cmd.Parameters.AddWithValue("#ID", box1.Text);
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
}
When using data-aware controls such as a ListView here, the controls are created with automatic unique IDs per data item. This means that you can have more than 1 of the same control (such as "box1" in this case) within the page that should be referenced by the data item (((LinkButton)sender).Parent which is ListViewDataItem, representing the row).
ListViewDataItem.FindControl will find controls of a specific server ID within its own child scope, allowing you to get values for controls within the same row of the button that is being clicked.

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

Populate ListView with data from server

I have a ListView on my checkout page with an ItemTemplate which build up a table of items ordered by customer. I want to add a total in the footer of the table, I have the following markup:
<asp:ListView ID="lvOrderSummary" runat="server">
<LayoutTemplate>
<table id="tblOrderSummary">
<tr>
<td><b>Title</b></td>
<td><b>Cost</b></td>
</tr>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
<tr>
<td><b>Total Cost:</b></td>
<td><%# GetTotalCost().ToString()%></td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("Title") %></td>
<td><%#Eval("Cost") %> </td>
</tr>
</ItemTemplate>
</asp:ListView>
I have a server side method called GetTotalCost that return the value I require. The problem I'm having is that this method is never called.
I have also tried and instead of using:
<td><%# GetTotalCost().ToString()%></td>
I've tried using
<td id="tdTotal" runat="server"></td>
---------------
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TableCell td = ((TableCell)this.FindControl("lvOrderSummary_tdTotal"));
}
}
Check this article for an example how to display a total in the ListView.
Basically you can add a label in the layout template:
<asp:ListView ID="lvOrderSummary" runat="server"
OnPreRender="lvOrderSummary_PreRender" ...>
<LayoutTemplate>
...
<td><asp:Label ID="lblTotalCost" runat="server" Text="Total"/></td>
..
</LayoutTemplate></asp:ListView>
And then you set the label's text in the PreRender event handler:
protected void lvOrderSummary_PreRender(object sender, EventArgs e)
{
Label lbl = lvOrderSummary.FindControl("lblTotalCost") as Label;
lbl.Text = GetTotalCost().ToString();
}
Try
Dim strcon As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=D:\webarticles\App_Data\mydatabase.mdf;Integrated Security=True;User Instance=True"
Dim con As New SqlConnection(strcon)
con.Open()
Dim da As SqlDataAdapter
Dim ds As New DataSet
Dim sqlstring As String = "SELECT * FROM tblstudent "
da = New SqlDataAdapter(sqlstring, con)
da.Fill(ds)
DetailsView1.DataSource = ds.Tables(0)
DetailsView1.DataBind()
Catch ex As Exception
MsgBox("There is some Error")
End Try
Another data handeling control is DetailsView control which gives you the ability to display, delete, edit, insert a single record at a time from its associated data source. The DetailsView control does not support sorting.By default, the DetailsView control displays each field of a record on its own line.

Resources