I have a repeater defined as
<asp:Repeater id="rep1" runat="server">
<ItemTemplate>
<%#Eval("name")%>
</ItemTemplate>
</asp:Repeater>
The code behind is as
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #"Data Source=XXXXXX;Trusted_Connection=yes;database=master";
xconn.Open();
lbl1.Text = "Connected to SQL";
SqlCommand ycmd = new SqlCommand("select * from student",xconn);
SqlDataReader dr = ycmd.ExecuteReader();
cdcatalog.DataSource = dr;
cdcatalog.DataBind();
}
catch (Exception)
{
lbl1.Text= "Cannot connect to SQL";
}
Why does it not bind the data in the repeater?
Why are you binding data readers to a repeater? I would recommend you using strongly typed objects. So start by defining a model that will represent your data:
public class Student
{
public string Name { get; set; }
}
then a method to fetch those students:
public IEnumerable<Student> GetStudents()
{
using (var conn = new SqlConnection("Data Source=XXXXXX;Trusted_Connection=yes;database=master"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Students;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new Student
{
Name = reader.GetString(reader.GetOrdinal("Name"));
}
}
}
}
}
and then bind the repeater:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rep1.DataSource = GetStudents().ToArray();
rep1.DataBind();
}
}
and in the view:
<asp:Repeater id="rep1" runat="server">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:Repeater>
Also note that the name of the repeater is rep1 so that's what you should use in your code behind.
the ID of your repeater is rep1 whereas you are databinding cdcatalog. I guess your problem is there. What is this cdcatalog?
Related
Asp.code
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged1" DataTextField="socialname">
<asp:ListItem text="select">Comment using</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:prakashConnectionString %>" SelectCommand="SELECT [socialname] FROM [socialnetwork]"></asp:SqlDataSource>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
C# code
SqlConnection con = new SqlConnection("****");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bindddl();
BindTitle();
Label3.Text = DropDownList1.Items[0].Text;
}
}
protected void Bindddl()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from socialnetwork", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataTextField = "socialname";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();
con.Close();
}
protected void BindTitle()
{
if (DropDownList1 != null)
{
foreach (ListItem li in DropDownList1.Items)
{
li.Attributes["title"] = "social/" + li.Value; // it ll set the value of items in dropdownlist as tooltip
}
}
}
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
BindTitle();
Label3.Text = DropDownList1.SelectedItem.Text;
Label3.Text = "Commented by";
}
You have not assigned the DataSource:
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "socialname";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();
But you have used both, the DataSourceID on the aspx and the codebehind DataSet. For the SqlDataSource you have not selected the name but only:
SELECT [socialname] FROM [socialnetwork]
Just remove the SqlDataSource, it is simply redundant.
As an aside, i suggest to use the using-statement for the connection and the dataadapter to ensure that all unmanaged resources are disposed and the connection gets closed (even on error):
DataSet ds = new DataSet();
using(SqlConnection con = new SqlConnection("****"))
using(SqlDataAdapter da = new SqlDataAdapter("select * from socialnetwork", con))
da.Fill(ds); // you don't need to open/close the connection with Fill
DropDownList1.DataSource = ds.Tables[0];
// ...
I ran into a similar issue using an asp.net listbox. I changed the name of the column I was returning into the display value field to match the name in the error condition and that resolved the issue. For example I was getting this error:
[HttpException (0x80004005): DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'DisplayValue'.]
The value that was being returned from my SELECT statement was held in a column named theValue. I changed the column alias to be DisplayValue instead:
SELECT theValue as DisplayValue
FROM whateverTable
note I am working in VS 2012.
I'm deleting a single database record from a listview and after deleting I try to navigate in my listview using listView1.selectedindex property, but I have noticed that it highlights the incorrect record (for example I set listView1.selectedindex to 1 but it displays a record which has index 0) . What is wrong? Please help!
protected void deleteButton_Click(object sender, EventArgs e)
{
int id = int.Parse(((Label)ListView1.Items[ListView1.SelectedIndex].FindControl("idLabel")).Text);
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
BindDataFromBaseToListView method looks so:
private void BindDataFromBaseToListView()
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("select * from Employee", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
ListView1.DataSourceID = null;
ListView1.DataSource = dTable;
ListView1.DataBind();
}
conn.Close();
}
Instead of using deleteButton_Click event you could use your ListView's OnItemCommand event to get the selected row values and delete the item that you want like the code below:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
int id = 0;
if(int.TryParse((e.Item.FindControl("idLabel") as Label).Text, out id))
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
}
}
And on your control's element will look like this:
<asp:ListView ID="ListView1" runat="server" OnItemCommand="ListView1_ItemCommand" .. >
...
<ItemTemplate>
<asp:Button runat="server" CommandName="delete" Text="Delete" ID="DeleteButton" />
...
Let me know if you still have issue with it.
I am new to ASP.NET
Someone in this forum helped me how to get the dropdown list work wth user countrol and it is working.
In my user control file, VendorListControl.ascx, I have this code below. Please assume that the VendorListControl.ascx.cs works correctly, which is when I select a VendorName, it will fired "ddlVendor_SelectedIndexChanged" to refreshed the "ddlVendorBUList" dropdown list.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="VendorListControl.ascx.cs" Inherits="MyNamespace.VendorListControl" %>
<asp:DropDownList runat="server" ID="ddlVendorList" onselectedindexchanged="ddlVendor_SelectedIndexChanged" AutoPostBack="True" />
<asp:DropDownList runat="server" ID="ddlVendorBUList" AutoPostBack="True" />
<asp:Label runat="server" ID="lblMessage" />
My VendorListControl.ascx.cs code:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MyNamespace
{
public partial class VendorListControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillVendors();
}
}
protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
{
int VendorID = Convert.ToInt32(ddlVendorList.SelectedValue.ToString());
FillVendorBU(VendorID);
}
private void FillVendors()
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorID, VendorName FROM MDF_Vendor";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd; ;
conn.Open();
dAdapter.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
this.ddlVendorList.DataSource = objDs.Tables[0];
this.ddlVendorList.DataTextField = "VendorName";
this.ddlVendorList.DataValueField = "VendorID";
this.ddlVendorList.DataBind();
this.ddlVendorList.Items.Insert(0, "-- Select --");
}
else
{
this.lblMessage.Text = "No Vendor Found";
}
}
private void FillVendorBU(int VendorID)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorBUID, VendorBUName FROM dbo.MDF_VendorBU WHERE VendorID = #VendorID";
cmd.Parameters.AddWithValue("#VendorID", VendorID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlVendorBUList.DataSource = objDs.Tables[0];
ddlVendorBUList.DataTextField = "VendorBUName";
ddlVendorBUList.DataValueField = "VendorBUID";
ddlVendorBUList.DataBind();
ddlVendorBUList.Items.Insert(0, "--Select--");
}
else
{
lblMessage.Text = "No states found";
}
}
}
}
Next, in my CreateNewRecord.aspx page, I have this code to include both dropdown list from user control. And I can see the dropdown lists works properly.
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl runat="server" />
</td>
</tr>
The problem is related to the ID of those two dropdown lists. When I attemp to do the insert record, it seems not to detect the ID for "ddlVendorList" and "ddlVendorBUList" come from user control ascx page. Error " The name 'ddlVendorList' does not exist in the current context"
ExecuteInsert(ddlVendorList.SelectedItem.Text,
ddlVendorBUList.SelectedItem.Text,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
Response.Write("<b>Record was successfully added!</b>");
I know I am new to ASP.NET, so please help.
You can put two properties in your VendorListControl to get the ddlVendorList selectedItem text and the ddlVendorBUList selectedItem text.
In VendorListControl.ascx.cs :
public string GetDdlVendorListSelectedItemText
{
get { return this.ddlVendorList.text; }
}
public string GetDdlVendorBUListSelectedItemText
{
get { return this.ddlVendorBUList.text; }
}
Then from your page CreateNewRecord, you can access those properties. You just need to add an id to your control :
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl id="vendorListControl" runat="server" />
</td>
</tr>
And you can access your properties like this in CreateNewRecord.aspx.cs :
ExecuteInsert(this.vendorListControl.GetDdlVendorListSelectedItemText,
this.vendorListControl.GetDdlVendorBUListSelectedItemText,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
You define public property who return SelectedItem.Text in your UserControl.
User Control (Ascx)
public string YourValue
{
get
{
return ddlVendorList.SelectedItem.Text;
}
}
Page (Aspx)
You can use your public property : YourValue.
ExecuteInsert(YourValue,
....... );
Nota : if you wish set value, you define setter on your property
After your update add theses properties
public string YourDdlVendorListSelectedItemText
{
get
{
return this.ddlVendorList.text;
}
}
public string YourDdlVendorBUListSelectedItemText
{
get
{
return this.ddlVendorBUList.text;
}
}
I got the below code from internet. It is working properly. I have added paging also. When I'm just sorting, it is working properly. When I am changing the page index, the sorting is lost.
Here is the client side code that set a gridview with 20 items per page, using the sort linked to the "GridView1_Sorting" method in the server side code.
Client side
<asp:GridView ID="GridView1" runat="server" DataKeyNames="eno" AutoGenerateColumns="False" PageSize="20" AllowPaging="True" AllowSorting="True" OnSorting="GridView1_Sorting" CellPadding="4">
<Columns>
<asp:TemplateField HeaderText="Employee no" SortExpression="eno">
<ItemTemplate>
<%#Eval("eno")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp name" SortExpression="empname">
<ItemTemplate>
<%#Eval("empname")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary" SortExpression="sal">
<ItemTemplate>
<%#Eval("sal")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And now the server side code:
Server side
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridData();
}
}
void GridData()
{
sqlcmd = new SqlCommand("select * from emp", sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["dt"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
private string GVSortDirection
{
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private string GetSortDirection()
{
switch (GVSortDirection)
{
case "ASC":
GVSortDirection = "DESC";
break;
//assign new direction as ascending order
case "DESC":
GVSortDirection = "ASC";
break;
}
return GVSortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = (DataTable)Session["dt"];
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
string sortDirection = GetSortDirection();
dataView.Sort = e.SortExpression + " " + sortDirection;
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridData();
}
}
When you page, the PageIndexChanging event is called. This in turn runs the GridData() procedure, which sets the data source for the gridview to be a data table containing records from the emp table, with no particular sort order.
What you should do is to take the code that you've written in your GridView1_Sorting event-handler, and include this within the GridData routine, so that whenever the grid is populated with data - whether when the page first loads, when the page index is changed or when the gridview is sorted - the gridview is based on a sorted dataview, rather than an unsorted data table.
The way you are maintaining SortDirection using GetSortDirection, in same fashion maintain SortExpression.
Happy coding!!!
Have a look to this article, may you will get what you want
The following code sample is for sorting a GridView formed With a DataSet.
Source: http://www.highoncoding.com/Articles/176_Sorting_GridView_Manually_.aspx
But it is not displaying any output.
There is no problem in sql connection.
I am unable to trace the error, please help me.
Thank You.
public partial class _Default : System.Web.UI.Page
{
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
private DataSet GetData()
{
SqlConnection cnn = new SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;");
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES", cnn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression, string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
aspx page
asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView1_Sorting">
/asp:GridView>
Problem is with Page Load event when you fill the data you add it inside if(!IsPostBack) condition .
In this article, there is explained how to sort the GridView data in ASP.NET.
GridvIew control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data as well.
http://www.dotnetfunda.com/articles/article1598-how-to-sort-the-gridview-data-in-aspnet.aspx
//Code Behind
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvbind();
}
}
protected DataSet gvbind() // Binding the gridview using Dataset and I am using stored procedure "Proc_Displayinfo"
{
con.Open();
SqlCommand command = new SqlCommand("Proc_Displayinfo", con);
SqlDataAdapter adpt = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adpt.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
con.Close();
return ds;
}
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
protected void Gridview1_Sorting(object sender, GridViewSortEventArgs e)
{
gvbind();
DataTable dt = gvbind().Tables[0];
{
string SortDir = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
SortDir = "Desc";
}
else
{
dir = SortDirection.Ascending;
SortDir = "Asc";
}
DataView sortedView = new DataView(dt);
sortedView.Sort = e.SortExpression + " " + SortDir;
GridView1.DataSource = sortedView;
GridView1.DataBind();
}
}
// Source Code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="StudentId" onsorting="Gridview1_Sorting" AllowSorting="True">
<asp:TemplateField HeaderText="StudentID" SortExpression="StudentID">
<ItemTemplate>
<asp:Label ID="LBLStudentID" runat="server" Text='<%# Eval("StudentID") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TXTStudentID" runat="server" Text='<%# Eval("StudentID") %>'></asp:TextBox>
</EditItemTemplate>