My C# Code
public partial class Message : System.Web.UI.Page
{
String strconn = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
members();
}
public void members()
{
SqlConnection con = new SqlConnection(strconn);
con.Open();
try
{
string str = "Select Users.Username,Users.Name,ProfilePic.Pathh From Users FULL OUTER JOIN ProfilePic ON Users.username = ProfilePic.Username ORDER BY Users.Sno";
SqlCommand cmd = new SqlCommand(str,con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
repMembers.DataSource = ds;
repMembers.DataBind();
GridView1.DataSource = ds;
GridView1.DataBind();
cmd.Dispose();
con.Close();
}
catch(Exception ex) {
lbMembers.Text = ex.ToString();
}
}
}
And My HTML Code
<asp:Repeater ID="repMembers" runat="server" >
<asp:ItemTemplate >
<div style="width:100%; border-bottom:#ffffff 2px solid;"> <asp:Image ID="Image4" runat="server" ImageUrl='<%#Eval("Pathh") %>' width="60px" Height="60px"/> <asp:Label ID="lb" runat="server" Text='<%#Eval("Username") %>'></asp:Label><br/><asp:Label ID="lbname" runat="server" Text='<%#Eval("Name") %>'></asp:Label><br/></div>
</asp:ItemTemplate>
</asp:Repeater>
My Table is absolutely correct and is working, i checked it with Grid View. It gives me the "Name","Username", and "Path" Stored.
I checked it with SQL query and displayed it in grid view.
This is the Photo of my table,it is the combination of two tables
Use ItemTemplate instead of asp:ItemTemplate. There's also a typo with the word "Pathh", does this solve your issue?
<ItemTemplate >
<div style="width:100%; border-bottom:#ffffff 2px solid;">
<asp:Image ID="Image4" runat="server" ImageUrl='<%#Eval("Path") %>' width="60px" Height="60px"/>
<asp:Label ID="lb" runat="server" Text='<%#Eval("Username") %>'></asp:Label>
<br/>
<asp:Label ID="lbname" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
<br/>
</div>
</ItemTemplate>
Related
I have an issue trying to display image in my DataList from the database and have access to the database that I'm pulling my images from. But when I run the WebForm the image does not appear, what is wrong in my codes?
<asp:DataList ID="DataList1" runat="server" DataKeyField="dishID" DataSourceID="SqlDataSource1" BorderStyle="Solid" GridLines="Both" RepeatColumns="4" RepeatDirection="Horizontal" Width="1259px" >
<ItemTemplate>
<table class="auto-style1">
<tr><td>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "FoodPictures/" + Eval("dishImage") %>' />
This is how I'm retrieving from the database:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(_connStr);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Dish";
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
conn.Close();
DataList1.DataSource = dt;
DataList1.DataBind();
conn.Close();
}
I think Your Page do not get image on proper path....
use
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "../FoodPictures/" + Eval("dishImage") %>' />
Or
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "~/FoodPictures/" + Eval("dishImage") %>' />
Try this..
Assuming if dishImage is a name like imagename.jpg stored in database then try Convert.ToString(Eval("dishImage")) like:
<asp:Image ID="Image1" ImageUrl='<% # "~/FoodPictures/" + Convert.ToString(Eval("dishImage")) %>' runat="server" />
I have a GridView within a LoginView that I am getting an Index Out Of Range error with. When I display the # of rows in the GridView it always shows 0 which is causing this error.
Is there something specific that I need to be doing to get a GridView
to properly work within a LoginView?
Below is the code that is being run when I click on a button in the GridView and the error only comes up on the GridView row = gv.Rows[e.RowIndex]; line. If I use only e.RowIndex I do not get the error and it will actually return the proper number. If I do gv.DataKeys.Count it will return the correct count. If I do gv.Rows.Count it will always be 0. I think it has something to do with a PostBack because if I do a row count in my page_load then it returns the correct count. Please let me know if there is anything else that you need for me to post?
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
GridView gv = ReviewLoginView.FindControl("gvReview") as GridView;
GridViewRow row = gv.Rows[e.RowIndex];
string Id = (row.FindControl("lblID") as Label).Text;
string constr = System.Configuration.ConfigurationManager.AppSettings["ObservationCardCS"];
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("cardReview"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", Id);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
gv.EditIndex = -1;
this.BindGrid();
}
catch (Exception ex)
{
GridView gv = ReviewLoginView.FindControl("gvReview") as GridView;
int index = e.RowIndex;
lblError.ForeColor = System.Drawing.Color.Red;
lblError.Text = ex.Message + " " + index.ToString() + " " + gv.Rows.Count;
}
}
Below is the LoginView from the aspx page.
<asp:LoginView runat="server" ViewStateMode="Disabled" ID="ReviewLoginView">
<LoggedInTemplate>
<%--<AnonymousTemplate>--%>
<div>
<asp:GridView ID="gvReview" runat="server" AutoGenerateColumns="false" DataKeyNames="ID"
OnRowDataBound="OnRowDataBound" OnRowDeleting="OnRowDeleting" EnableViewState="true"
EmptyDataText="No records have been added." AllowSorting="true" ShowHeaderWhenEmpty="true"
AlternatingRowStyle-BackColor="#e0e0e0" HeaderStyle-BackColor="#d0d0d0" ViewStateMode="Disabled"
EnableSortingAndPagingCallbacks="false">
<Columns>
<asp:TemplateField HeaderText="ID" ShowHeader="false" Visible="true">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>' CssClass="cmsID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User">
<ItemTemplate>
<asp:Label ID="lblSubmittedBy" runat="server" Text='<%# Eval("submittedBy") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%# Eval("location") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="lblSubmittedDate" runat="server" Text='<%# Eval("submittedDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="What Was Observed?">
<ItemTemplate>
<asp:Label ID="lblWhatWasObserved" runat="server" Text='<%# Eval("whatWasObserved") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="What Action Was Taken?">
<ItemTemplate>
<asp:Label ID="lblWhatActionWasTaken" runat="server" Text='<%# Eval("whatActionWasTaken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="What Agreement Was Reached?">
<ItemTemplate>
<asp:Label ID="lblWhatAgreementWasReached" runat="server" Text='<%# Eval("whatAgreementWasReached") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="btnSubmit" runat="server" Text="Edit" CssClass="editbutton" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Review" ButtonType="Button" ShowDeleteButton="true" DeleteText="Review" />
</Columns>
</asp:GridView>
</div>
</LoggedInTemplate>
<%--</AnonymousTemplate>--%>
<AnonymousTemplate>
You must login to view submitted Observation Cards.
</AnonymousTemplate>
</asp:LoginView>
Below is the BindGrid()
private void BindGrid()
{
try
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ObservationCardCS"]);
{
SqlCommand comm = new SqlCommand("cardSelectNew2", conn);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = comm;
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.AddWithValue("#Begin", "1/1/1950");
comm.Parameters.AddWithValue("#End", "12/31/2049");
comm.Parameters.AddWithValue("#Reviewed", "0");
comm.Parameters.AddWithValue("#OrderBy", "CH.id");
comm.Parameters.AddWithValue("#AscDesc", "Asc");
comm.Parameters.AddWithValue("#DateRange", "Last 30 Days");
comm.Connection = conn;
sda.SelectCommand = comm;
DataTable dt = new DataTable();
sda.Fill(dt);
GridView gv = ReviewLoginView.FindControl("gvReview") as GridView;
gv.DataSource = dt;
gv.DataBind();
}
}
catch (Exception ex)
{
lblError.ForeColor = System.Drawing.Color.Red;
lblError.Text = ex.Message;
}
}
Below is my page_load
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
lblError.ForeColor = System.Drawing.Color.Black;
lblError.Text = "";
}
}
You are on the right track! But without seeing the whole class and markup we can only speculate.
Check that you are not clearing or rebuilding the data on the page load event handler, if the Grid and datasource is defined in the markup then it should cache or requery the data between page postbacks, check that you have set EnableRowCache on the GridView so that you dont have to re-query for the data during postbacks.
It looks like you are using the #OldSchool BindGrid() data load pattern, perhaps the simplest solution may be to ensure that the data is loaded first by calling BindGrid before you try to access the rows:
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
this.BindGrid();
try
{
... delete logic
this.BindGrid(); // re-load after the change
}
catch (Exception ex)
{
...
}
}
Without enabling the row cache though you have to ensure that the same data is loaded into the grid in the same order or delete logic like this based on row index (instead of the primary key of the row) could result in you deleting the wrong data row.
i am creating labels dynamically in list view, the labels are placed inside the div tag and i want the cssclass of the label to be changed for each label. i am getting names of the label dynamically from database and that database contains cssclasses for each name. so how can i bind the cssclass dynamically to the div tag? following is the code
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<div class="sidebar-links">
<div class="link-blue">
<i class="fa fa-archive"></i><asp:Label ID="Label1" runat="server" Text='<% #Bind ("mdl_name") %>' ></asp:Label>
</div>
</div>
</ItemTemplate>
</asp:ListView>
This is the codebehind
DataTable dt1 = (DataTable)Session["SessionUserInfo"];
String type = dt1.Rows[0]["user_id"].ToString();
SqlConnection conn = new SqlConnection("Data Source=BABA; Database=afaqandco; Integrated Security=true");
SqlCommand cmd = new SqlCommand("SELECT ma.*, m.* FROM tblmdluserassociation AS ma INNER JOIN tbl_module AS m ON ma.mdl_id=m.mdl_id WHERE ma.user_id='"+type+"'", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
ListView1.DataSource = dt;
ListView1.DataBind();
You should add ItemDataBound method to the list view and then create it in code behind as follows:
<asp:ListView ID="ListView1" runat="server" ItemPlaceholderID="itemplaceholder" OnItemDataBound="ListViewMenu_ItemDataBound">
<LayoutTemplate>
<asp:PlaceHolder ID="itemplaceholder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<div class="sidebar-links">
<div id="MYDIV" runat="server">
<a href="#"><i class="fa fa-archive"></i>
<asp:Label ID="Label1" runat="server" Text='<% #Bind("mdl_name") %>'></asp:Label></a>
</div>
</div>
</ItemTemplate>
</asp:ListView>
Code Behind
protected void ListViewMenu_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem listViewDataItem = e.Item as ListViewDataItem;
HtmlGenericControl divControl = e.Item.FindControl("MYDIV") as HtmlGenericControl;
DataRowView dataRow = ((DataRowView)listViewDataItem.DataItem);
divControl.Attributes.Add("class", dataRow["CLASS"].ToString());
}
}
I want to display three column field as dropdownlist and other in textbox format.I have wrote the code to display the dropdownlist value from my database but its not working.I have attached my code for your referal
<asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="FacultyName">
<ItemTemplate>
<asp:Label ID="lblfaculty" runat="server" Text='<%%# Eval("facultyname") %>>' Visible="false" />
<asp:DropDownList ID="ddlfaculty" runat="server" OnSelectedIndexChanged="ddlfaculty_SelectedIndexChanged"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject">
<ItemTemplate>
<asp:Label ID="lblsubject" runat="server" Text='<%%# Eval("subject") %>>' Visible="false" />
<asp:DropDownList ID="ddlsubject" runat="server" OnSelectedIndexChanged="ddlsubject_SelectedIndexChanged"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject">
<ItemTemplate>
<asp:Label ID="lblsubject" runat="server" Text='<%%# Eval("subject") %>>' Visible="false" />
<asp:DropDownList ID="ddlsubject" runat="server" OnSelectedIndexChanged="ddlsubject_SelectedIndexChanged1"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblsubject" runat="server" Text='<%%# Eval("sethour") %>>' Visible="false" />
<asp:TextBox ID="ddlsethour" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblcount" runat="server" Visible="false" />
<asp:TextBox ID="Count" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind:
public partial class transhonorarium : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlfaculty_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
SqlDataAdapter cmd = new SqlDataAdapter("select facultyname from faculty", con);
DataTable dt = new DataTable("dt");
cmd.Fill(dt);
Gv1.DataSource = dt;
Gv1.DataBind();
}
}
protected void ddlsubject_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
SqlDataAdapter cmd = new SqlDataAdapter("select subject from assign where facultyname=#facultyname", con);
DataTable dt = new DataTable("dt");
cmd.Fill(dt);
Gv1.DataSource = dt;
Gv1.DataBind();
}
}
}
You need to change one thing here.
AutoGenerateColumns = true. Because of this, you will be able to see the columns assigned and its data.
Secondly,
You need to Bind your Gridview as required on Page_load or somewhere you want. Here is for page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Gv1.DataSource = Somesource;
Gv1.DataBind();
}
}
See the Bind Data
public void BindData()
{
SqlCommand comd = new SqlCommand("SELECT * FROM Yourtablename", con);
SqlDataAdapter da = new SqlDataAdapter(comd);
DataTable dt = new DataTable();
da.Fill(dt);
GV1.DataSource = dt;
GV1.DataBind();
}
Hope that helps
Call the DataBind() Method of your Gridview when your data changes.
I'd do something like this:
protected override void OnPreRender(Eventargs e)
{
base.OnPreRender(e);
GV1.DataBind();
}
in order to fill your dropdown lists ,you should implement _RowDataBound event and to update dataset bases on your selection you should also implement RowCommand event for your dropdown objects.
btw. in ddlsubject_SelectedIndexChanged, you also need to add parameter to your sql command to get your sql string working ,
hope this helps.
I'm using a Datalist to show countries list each record having a Gridview containing a list of states and each state having a Dropdownlist for cities. I am using a hidden field to get the ID of country to retrieve the name of state for every record by using Eval("C_ID") in the hidden field. But it raises ArgumentOutOfRangeException. I'm not able to know what I'm doing wrong.
Here is the code for Datalist:
<asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" onitemdatabound="DataList1_ItemDataBound" >
<ItemTemplate>
<table border="1px">
<tr>
<td>
<%#Eval("C_Name") %><br />
<asp:HiddenField ID="HiddenField1" Value='<%#Eval("C_ID") %>' runat="server" />
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="State Cities">
<ItemTemplate >
<asp:CheckBox ID="CheckBox1" runat="server" />
<%#Eval("S_Name") %>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
and this is code behind:
public partial class AdvancedTable : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("select * from Country", con);
con.Open();
da.Fill(ds, "Country");
con.Close();
DataList1.DataSource = ds;
DataList1.DataBind();
}
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
SqlDataAdapter da2 = new SqlDataAdapter();
da2.SelectCommand = new SqlCommand("select * from State where C_ID='"+((HiddenField)DataList1.Items[e.Item.ItemIndex].FindControl("HiddenField1")).Value+"'",con);
con.Open();
da2.Fill(ds, "State");
con.Close();
((GridView)e.Item.FindControl("GridView1")).DataSource = ds.Tables["State"];
((GridView)e.Item.FindControl("GridView1")).DataBind();
}
}
Perhaps, instead of DataList1.Items[e.Item.ItemIndex].FindControl("HiddenField1")
Just use e.Item.FindControl("HiddenField1")
Instead, you can do the following:
<asp:DropDownList ID="DropDownList1" runat="server" DataSource="<%# GetList((int)Eval("C_ID"))%>">
</asp:DropDownList>
In the code Behind
protected DataTable GetList(int id){ }