I am trying to use grid view to display a join of several tables(Empdetail,Department,Country,State,City,Qualification). The main table(Empdetail) has different IDs(eg DeptID) which refer to the primary key ID present in the tables. I want department(and other fields) to appear as dropdown choice while updating the gridview but I am facing issues while populating the drop down list and making the edit button fire. The following is the code.
.ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Database.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Employee Database</title>
<script src="Themes/js/bootstrap.js" type="text/javascript"></script>
<script src="Themes/js/jquery.min.js" type="text/javascript"></script>
<script src="Themes/js/npm.js" type="text/jahttp://www.aspsnippets.com/Articles/Simple-Insert-Select-Edit-Update-and-Delete-in-ASPNet-GridView-control.aspxvascript"></script>
<script src="Themes/js/bootstrap.min.js" type="text/javascript"></script>
<script type = "text/javascript" src = "Scripts/jquery-1.3.2.min.js"></script>
<script type = "text/javascript" src = "Scripts/jquery.blockUI.js"></script>
<script type = "text/javascript">
//to create a loading effect
function BlockUI(elementID) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(function() {
$("#" + elementID).block({ message: '<table align = "center"><tr><td>' +
'<img src="Images/loadingAnim.gif"/></td></tr></table>',
css: {},
overlayCSS: {backgroundColor:'#000000',opacity: 0.6, border:'3px solid #63B2EB'
}
});
});
prm.add_endRequest(function() {
$("#" + elementID).unblock();
});
}
$(document).ready(function() {
BlockUI("dvGrid");
$.blockUI.defaults.css = {};
});
</script>
<link href="Themes/css/bootstrap-theme.min.css" rel="stylesheet" type="text/css" />
<link href="Themes/css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="Themes/css/bootstrap-theme.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div id = "dvGrid">
<asp:ScriptManager runat="server" ID="sm">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width = "900px" AlternatingRowStyle-BackColor = "#b3e6ff"
AutoGenerateColumns="false" AllowPaging="true" OnRowDataBound="OnRowDataBound"
HeaderStyle-BackColor = "#0080ff" DataKeyNames="ID"
PageSize="10" class="table table-bordered" ShowFooter="true"
onrowediting="EditEmployee" onrowupdating="UpdateEmployee"
onrowcancelingedit="CancelEdit" OnRowDeleting="DeleteEmployee"
EmptyDataText="No records Selected.">
<Columns >
<asp:TemplateField >
<ItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%# Eval("ID") %>' /><!--Primary key,no update and insert,auto generated-->
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "EmpCode">
<ItemTemplate>
<asp:Label ID="lblEmpCode" runat="server"
Text='<%# Eval("EmpCode")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpCode" runat="server"
Text='<%# Eval("EmpCode")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmpCode" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server"
Text='<%# Eval("EmpName")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server"
Text='<%# Eval("EmpName")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtName" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "DOJ">
<ItemTemplate>
<asp:Label ID="lblDOJ" runat="server"
Text='<%# Eval("DOJ")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDOJ" runat="server"
Text='<%# Eval("DOJ")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDOJ" class="form-control" Width = "100px"
MaxLength = "15" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "120px" HeaderText = "Department">
<ItemTemplate>
<asp:Label ID="lblDepartment" runat="server"
Text='<%# Eval("DeptName")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID = "Depddl" runat="server" Width="100px" >
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox class="form-control" ID="txtDepartment" Width = "140px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server"
Text='<%# Eval("CoName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCountry" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "State">
<ItemTemplate>
<asp:Label ID="lblState" runat="server"
Text='<%# Eval("SName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtState" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server"
Text='<%# Eval("CiName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCity" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Qualification">
<ItemTemplate>
<asp:Label ID="lblQualification" runat="server"
Text='<%# Eval("QName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtQualification" class="form-control" Width = "80px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument = '<%# Eval("ID")%>' OnClick = "DeleteEmployee"
OnClientClick = "return confirm('Do you want to delete?')"
Text = "Delete" >
</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add"
class="btn-primary" type="button" OnClick = "AddNewEmployee"/>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Codebehind(aspx.cs/c#)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
string constr = ConfigurationManager.ConnectionStrings["SQLDbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
protected void EditEmployee(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
{
//Find the DropDownList in the Row
SqlConnection con = new SqlConnection(constr);
DropDownList Depddl = (DropDownList)e.Row.FindControl("Depddl");
string query = "SELECT ID,DeptName FROM Department;";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
Depddl.DataSource = GetData(cmd);
Depddl.DataTextField = "DeptName";
Depddl.DataValueField = "ID";
Depddl.DataBind();
con.Close();
//Add Default Item in the DropDownList
Depddl.Items.Insert(0, new ListItem("Please select"));
//Select the Department ofEmployee in DropDownList
string Department = (e.Row.FindControl("lblDepartment") as Label).Text;
Depddl.Items.FindByValue(Department).Selected = true;
}
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void UpdateEmployee(object sender, GridViewUpdateEventArgs e)
{
string city = (GridView1.Rows[e.RowIndex].FindControl("Depddl") as DropDownList).SelectedItem.Value;
string ID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblID")).Text;
string EmpCode = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtEmpCode")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtName")).Text;
string DOJ = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtDOJ")).Text;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Empdetail set EmpName=#EmpName," + "EmpCode=#EmpCode,"+ "DOJ=#DOJ where ID=#ID; " +
"select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ, "+
"Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from "+
"Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID "+
"JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID "+
"JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID;
cmd.Parameters.Add("#EmpCode", SqlDbType.VarChar).Value = EmpCode;
cmd.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = Name;
cmd.Parameters.Add("#DOJ", SqlDbType.VarChar).Value = DOJ;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
protected void DeleteEmployee(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from Empdetail where " +
"ID=#ID;" +
"select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ, Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value
= lnkRemove.CommandArgument;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private void BindData()
{
string query = "select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ,"+
"Department.ID, Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from "+
"Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID"+
" JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID"+
" JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
protected void AddNewEmployee(object sender, EventArgs e)
{
string ID = ((TextBox)GridView1.FooterRow.FindControl("txtID")).Text;
string EmpCode = ((TextBox)GridView1.FooterRow.FindControl("txtEmpCode")).Text;
string Company = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
/*cmd.CommandText = "insert into Empdetail(EmpCode, CompanyName) " +
"values(#CustomerID, #ContactName, #CompanyName);" +
"select CustomerID,ContactName,CompanyName from customers";
cmd.Parameters.Add("#CustomerID", SqlDbType.VarChar).Value = CustomerID;
cmd.Parameters.Add("#ContactName", SqlDbType.VarChar).Value = Name;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Company;*/
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
}
Note:- I have searched extensively and on multiple sites so I would really appreciate it if you can tell me the exact issue instead of navigating me to a link. I am new to the concept of Gridview so please critique the code with an open mind. Thanks in advance
In the aspx file I'd drop data sources for each dropdown, SqlDataSource for example. In the markup you can fully define each DDL and every row uses the same single instance of the datasource. On editing you need only capture the selected value to update.
So...the DataSource for the Department example...
. . .
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>"
SelectCommand="SELECT ID,DeptName FROM Department"
EnableCaching="True">
</asp:SqlDataSource>
Then in the GridView Template for Department...
<EditItemTemplate>
<asp:DropDownList ID = "Depddl" runat="server" Width="100px" >
DataSourceID="SqlDataSource1"
DataTextField="DeptName"
DataValueField="ID"
</asp:DropDownList>
</EditItemTemplate>
And in the code behind you can optionally select the current value for the DDL from a current value...or not...up to you.
protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e )
{
if ( e.Row.RowType == DataControlRowType.DataRow )
{
if ( e.Row.RowState.HasFlag( DataControlRowState.Edit ) )
{
DataRowView drv = (DataRowView) e.Row.DataItem;
DropDownList ddl = (DropDownList) e.Row.FindControl( "DropDownList1" );
ddl.SelectedValue = ((int) drv[ "ID" ]).ToString();
}
}
}
After commenting several segments of the code I realized that the issue was with the "OnRowDataBound" function.
Commenting these lines made the update button fire again:-
string Department = (e.Row.FindControl("lblDepartment") as Label).Text;
Depddl.Items.FindByValue(Department).Selected = true;
What I could gather from this is that I cannot access an Item template control that way. Commenting the lines made the page run smoothly. However it was at the cost of losing the functionality of auto-selecting the original data value. I would like to implement this and will post an update as soon as I can achieve this.
I have a query in which I have to add more than one column.
Result of query is stored DataTable and binding it to Repeater. But the problem is DataTable shows the columns name and not the names I specified in query.
HTML (Persons.aspx):
<body>
<form id="form1" runat="server">
<h1><b>Persons</b></h1>
<div style="float:right">
<asp:LinkButton ID="lnkAdd" runat="server" Text="Add" Style="margin-right:100px"></asp:LinkButton>
</div>
<br />
<br />
<asp:Repeater ID="rptPersons" runat="server">
<ItemTemplate>
<div style="float: left">
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Pic") %>' Width="100px" Height="100px" />
</div>
<div style="float:left;margin-left:10px;">
<asp:Label ID="lblName" runat="server" Text='<%# Eval("PersonName") %>'></asp:Label><br />
<asp:Label ID="lblPost" runat="server" Text='<%# Eval("Post") %>'></asp:Label><br />
<asp:Label ID="lblLocation" runat="server" Text='<%# Eval("Location") %>'></asp:Label><br />
<%--<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age") %>'></asp:Label><br />--%>
</div>
</ItemTemplate>
<SeparatorTemplate>
<div style="margin-left:20px"></div>
</SeparatorTemplate>
</asp:Repeater>
</form>
</body>
Stored procedure:
select
FirstName as PersonName,
ISNULL(Designation,'') + ',' + ISNULL(Organization,'') as Post,
ISNULL(tblPersons.City,'') + ',' + ISNULL(tblPersons.State,'') as Location,
GETDATE() - tblPersons.dob + '( DoJ :' + '' + ISNULL(tblPersons.doj,'') as Age,
tblPersons.photo_name as Pic
from
tblpersons
Logic class:
public class PersonsLogic
{
public DataTable GetPersons()
{
string Connection = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using(SqlConnection con = new SqlConnection(Connection))
{
SqlCommand cmd = new SqlCommand("spGetPersons", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
}
}
Persons.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Persons objPerson = new Persons();
PersonsLogic objLogic = new PersonsLogic();
DataTable dt = objLogic.GetPersons();
if (dt.Rows.Count > 0)
{
rptPersons.DataSource = dt;
rptPersons.DataBind();
}
else
{
}
}
i am creating an image gallery (images stored in Images folder,path saved in db) in the gridview
Each imagename is saved in dbwith and uinque id and the columnname : storyid.
can anyone tell me how to bind the indiviudal images "like" count in the lblcount
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="SM1">
</asp:ScriptManager>
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Font-Names="Arial"
OnRowCommand="GridView1_RowCommand1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:UpdatePanel runat="server" ID="up1" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button runat="server" ID="IncreaseButton" Text="Like" CommandName="Increase"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:Label runat="server" ID="lblCount"></asp:Label>
<div style="display: none;">
<asp:Label Text="<%#Bind('StoryId')%>" ID="lblStoryid" runat="server"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField DataImageUrlField="FilePath" ControlStyle-Width="100" ControlStyle-Height="100"
HeaderText="Preview Image">
<ControlStyle Height="100px" Width="100px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label Text="Description" runat="server" Visible="False"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label Text="<%#Bind('Description')%>" ID="lblImageid" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
public partial class Gallery : System.Web.UI.Page
{
private void bindimage()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.
ConnectionStrings["dbconnection"].ConnectionString;
string strQuery = "select * from story";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Increase")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Label listPriceTextBox = (Label)row.FindControl("lblStoryid");
int storyId = Convert.ToInt32(listPriceTextBox.Text);
string UserEmailid = "aditya.arjula#gmail.com";
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string strQuery = "INSERT INTO Likes(storyId,UserEmailid) VALUES(#storyId,#UserEmailid)";
string LikeCount = "SELECT COUNT(StoryId) FROM Likes Where StoryId=1001;;";
Label lblStoryid = (Label)row.FindControl("lblStoryid");
lblStoryid.Text = LikeCount;
SqlCommand cmd = new SqlCommand(strQuery);
SqlCommand cmdl = new SqlCommand(LikeCount);
cmdl.CommandType = CommandType.Text;
cmdl.Connection = con;
cmd.Parameters.AddWithValue("#storyId", storyId);
cmd.Parameters.AddWithValue("#UserEmailid", UserEmailid);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
cmdl.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
}
You just need to pull the number of likes out when you pull the story record down in your bindimage method e.g.
SELECT Story.StoryId, Max(Description) As Description, Count(Likes.StoryId) as LikeCount from Story
INNER JOIN Likes On Likes.StoryId = Story.StoryId
GROUP BY Story.StoryId
Then you can bind the count like
<asp:Label Text='<%# Bind("LikeCount")%>' runat="server" ID="lblCount"></asp:Label>
See this fiddle.
I've been looking for a solution to this problem for a while, and I have searched the net, but still can't get this to work. If I put my code in the default asp template it will work, but when I use my template I always get the listbox Selecetedindex as -1.
Here is my C# code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web.UI.WebControls;
public partial class permissaotop : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Droptopicoperfil_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=Microsoft SQL Server (SqlClient);Server=Server;Initial Catalog=Forum;uid=user;pwd=password;Connect Timeout=10;TrustServerCertificate=True ");
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "SP_vertopicoperfil";
comm.Parameters.AddWithValue("#id_topico", this.Droptopicoperfil.SelectedValue);
SqlDataReader rdr = comm.ExecuteReader();
lbpermitidotp.DataSource = rdr;
lbpermitidotp.DataTextField = "Nome";
this.lbpermitidotp.DataValueField = "Id";
lbpermitidotp.DataBind();
rdr.Close();
conn.Close();
conn.Open();
SqlCommand comm1 = conn.CreateCommand();
comm1.CommandType = CommandType.StoredProcedure;
comm1.CommandText = "[SP_naotopicoperfil]";
comm1.Parameters.AddWithValue("#id_topico", this.Droptopicoperfil.SelectedValue);
SqlDataReader rdr1 = comm1.ExecuteReader();
lbproibidotp.DataSource = rdr1;
lbproibidotp.DataTextField = "Nome";
this.lbproibidotp.DataValueField = "Id";
lbproibidotp.DataBind();
rdr1.Close();
conn.Close();
}
protected void BtnnaopermitirClick(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=Microsoft SQL Server (SqlClient);Server=NEVETS-LAPTOP\\NEVETS;Initial Catalog=Forum;uid=sa;pwd=sql;Connect Timeout=10;TrustServerCertificate=True ");
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "usp_inserirtopicoperfil";
comm.Parameters.AddWithValue("#id_topico", this.Droptopicoperfil.SelectedValue);
comm.Parameters.AddWithValue("#id_perfil", this.lbproibidotp.SelectedValue.ToString());
SqlDataReader rdr = comm.ExecuteReader();
if (this.lbproibidotp.SelectedIndex >= 0)
{
this.lbproibidotp.Items.RemoveAt(this.lbproibidotp.SelectedIndex);
}
lbpermitidotp.DataBind();
lbproibidotp.DataBind();
Droptopicoperfil.DataBind();
rdr.Close();
conn.Close();
Droptopicoperfil_SelectedIndexChanged(this, null);
}
protected void BtnpermitirClick(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=Microsoft SQL Server (SqlClient);Server=NEVETS-LAPTOP\\NEVETS;Initial Catalog=Forum;uid=sa;pwd=sql;Connect Timeout=10;TrustServerCertificate=True ");
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "SP_apagartopicoperfil";
comm.Parameters.AddWithValue("#id_topico", this.Droptopicoperfil.SelectedValue);
comm.Parameters.AddWithValue("#id_perfil", lbpermitidotp.SelectedValue.ToString());
SqlDataReader rdr = comm.ExecuteReader();
lbpermitidotp.DataSource = rdr;
if (this.lbpermitidotp.SelectedIndex >= 0)
{
this.lbpermitidotp.Items.RemoveAt(this.lbpermitidotp.SelectedIndex);
}
lbpermitidotp.DataBind();
lbproibidotp.DataBind();
Droptopicoperfil.DataBind();
rdr.Close();
conn.Close();
Droptopicoperfil_SelectedIndexChanged(this, null);
}
protected void Button1_Click(object sender, EventArgs e)
{
//testing listbox
Label3.Text =lbproibidotp.SelectedIndex).ToString();
//Always gets the result -1
}
}
Asp:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="permissaotop.aspx.cs" Inherits="permissaotop" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Content" Runat="Server">
<br />
<asp:Panel ID="pnlperfil" runat="server" GroupingText="Topicoperfil"
style="text-align: center; margin-top: 15px;"
ScrollBars="None" Height="607px"
HorizontalAlign="Center" Wrap="False" EnableTheming="False"
Direction="LeftToRight" Font-Size="Small" Width="711px">
<br />
<br />
<table align="left">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Perfil"></asp:Label>
<br />
</td>
<td>
<asp:DropDownList ID="Dropperfil" runat="server" Height="20px" Width="213px"
AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="Nome"
DataValueField="Id" >
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:forumConnectionString2 %>"
SelectCommand="SELECT * FROM [Perfil]"></asp:SqlDataSource>
<br />
</td>
<td>
</td>
</tr>
<tr>
<td >
<asp:Label ID="Label2" runat="server" Text="topico"></asp:Label>
<br />
</td>
<td >
<asp:DropDownList ID="Droptopicoperfil" runat="server" Height="19px"
style="margin-left: 3px" Width="213px" AutoPostBack="True"
DataSourceID="SqlDataSource2" DataTextField="nome" DataValueField="Id_topico"
>
<asp:ListItem Text="-Select-" Value="" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:forumConnectionString2 %>"
SelectCommand="SELECT * FROM [Topico]"></asp:SqlDataSource>
<br />
</td>
<td >
</td>
</tr>
<tr>
<td >
<asp:ListBox ID="lbpermitidotp" runat="server" Width="113px"
onselectedindexchanged="lbpermitidotp_SelectedIndexChanged"
ViewStateMode="Enabled"></asp:ListBox>
</td>
<td >
<asp:Button ID="btnproibirtp" runat="server" style="text-align: center"
Text=">>" onclick="BtnpermitirClick" />
<asp:Button ID="btnpermitirtp" runat="server" Text="<<"
onclick="BtnnaopermitirClick" />
<asp:Label ID="Label3" runat="server" style="background-color: #000000"
Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</td>
<td >
<asp:ListBox ID="lbproibidotp" runat="server" Width="100px"
ViewStateMode="Enabled"></asp:ListBox>
<br />
<br />
</td>
</tr>
</table>
</asp:Panel>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="AfterBody" Runat="Server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="Footer" Runat="Server">
</asp:Content>
How can I fix this?
I have an ASP.NET FileUpload control. In the code-behind file, I used class to insert values-
public void Insertcert()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
try
{
if (FileUpload1.HasFile)
{
byte[] productImage = FileUpload1.FileBytes;
String insertstring2 = #"insert into Cert(CertName, CertLogo)
values(#CertName, #CertLogo)";
SqlCommand cmd = new SqlCommand(insertstring2, conn);
cmd.CommandText = insertstring2;
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.Parameters.AddWithValue("#CertName", TextBox18.Text);
cmd.Parameters.Add("#CertLogo", SqlDbType.VarBinary).Value = productImage;
cmd.ExecuteNonQuery();
}
}
finally
{
conn.Close();
}
Executing it here-
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
Insertcert();
}
I am using Wizard control to insert Certifications of the Employee:
<asp:Wizard ID="Wizard1" runat="server"
OnFinishButtonClick="Wizard1_FinishButtonClick"
Width="266px" ActiveStepIndex="0">
<WizardSteps>
<asp:WizardStep ID="WizardStep1" runat="server" Title="Step 2">
<asp:Label ID="Label19" class="caption" runat="server" Text="Certification Name:"></asp:Label>
<asp:TextBox ID="TextBox18" class="box" runat="server"></asp:TextBox> <br /><br />
<asp:Label ID="Label20" class="caption" runat="server" Text="Certification Logo:"></asp:Label>
<asp:FileUpload ID="FileUpload1" class="box" runat="server" /> <br /><br />