Populate Accoridon from SQL Database Values - c#

I am creating an accordion that will be populated from a sql database. For example if the database has 5 records (title and description included) then the accordion would have 5 panels. The title bound to the panel title field and the body consisting of the of the description. Like the following image:
Here is what I have so far by using a DataList and adding the accordion to the item template.
<asp:DataList ID="DynamicAccordion" runat="server" DataKeyField="Id" RepeatDirection="Vertical">
<HeaderTemplate>
<!--items in here are rendered once for the entire table and can be title, etc...) -->
</HeaderTemplate>
<ItemTemplate>
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a runat="server" data-toggle="collapse" href="#collapseOne" data-parent="#accordion">
<asp:Label runat="server" Text='<%#Eval("Section") %>' ID="SectionTitle"></asp:Label>
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in">
<div class="panel-body">
<a runat="server" data-toggle="collapse" href="#collapseOne" data-parent="#accordion">
<asp:Label runat="server" Text='<%#Eval("Description") %>' ID="Description"></asp:Label>
</a>
</div>
</div>
</div>
</div>
</ItemTemplate>
<FooterTemplate>
<!--Same as the header template just the footer-->
</FooterTemplate>
</asp:DataList>
And here is the backend that would bind the accordion to the sql records:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
var data = DataAccess.GetCurrentProject();
try
{
//data.Columns.Add("hrefPath");
foreach (DataRow dr in data.Rows)
{
dr["SectionTitle"] = dr["Section"];
dr["Description"] = dr["Description"];
}
DynamicAccordion.DataSource = data;
DynamicAccordion.DataBind();
}
catch (Exception ex)
{
}
}
//Data Access class code
public static DataTable GetCurrentProject()
{
DataTable dt = new DataTable();
try
{
string sqlCommandText = "Select * FROM RequestData";
using (SqlConnection connect = new SqlConnection(strConn))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sqlCommandText, connect))
{
sda.Fill(dt);
}
}
}
catch (Exception ex)
{
throw;
}
return dt;
}
Any information to help in creating this dynamic accordion would be great.
Thanks

Use a for each loop in the aspx file to do this:
(Remember you will also need to append to your ID fields to make them unique, otherwise you will end up with duplicates)
<% foreach (DataRow dr in data.Rows) { %>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a runat="server" data-toggle="collapse" href="#collapseOne" data-parent="#accordion">
<%= dr["Section"] %>
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in">
<div class="panel-body">
<a runat="server" data-toggle="collapse" href="#collapseOne" data-parent="#accordion">
<%= dr["Description"] %>
</a>
</div>
</div>
</div>
<% } %>

Related

SignUp data not showing up in database in ASP.NET project

I am trying to make a signup page in my asp.net project where I am using SQL Server for my project. But the problem is that the data is not going to the database on clicking signup button.
Here is my code which I have tried for usersignup.aspx, usersignup.aspx.cs, web.config.
usersignup.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="usersignup.aspx.cs" Inherits="BookManagement.usersignup" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="container">
<div class="row">
<div class="col-md-8 mx-auto">
<div class="card" style="border-radius:30px;background: #e9efef;">
<div class="card-body">
<div class="row">
<div class="col">
<center>
<img src="imgs/generaluser.png" style="width:90px;height:90px;text-align:center;vertical-align:middle;"/>
</center>
</div>
</div>
<div class="row">
<h4 style="text-align:center;">User SignUp</h4>
</div>
<div class="row">
<div class="col">
<hr>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label>Full Name : </label>
<div class="form-group">
<asp:TextBox CssClass="form-control" ID="TextBox1" runat="server" Placeholder="Full Name"></asp:TextBox>
</div>
</div>
<div class="col-md-6">
<label>Date Of Birth : </label>
<div class="form-group">
<asp:TextBox CssClass="form-control" ID="TextBox2" runat="server" Placeholder="Date" TextMode="Date"></asp:TextBox>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6">
<label>Contact NO : </label>
<div class="form-group">
<asp:TextBox CssClass="form-control" ID="TextBox3" runat="server" Placeholder="Contact No" TextMode="Number"></asp:TextBox>
</div>
</div>
<div class="col-md-6">
<label>Email : </label>
<div class="form-group">
<asp:TextBox CssClass="form-control" ID="TextBox4" runat="server" Placeholder="Email" TextMode="Email"></asp:TextBox>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-4">
<label>State </label>
<div class="form-group">
<asp:DropDownList class="form-control" ID="DropDownList1" runat="server">
<asp:ListItem Text="Select" Value="Select" />
<asp:ListItem>Arunachal Pradesh</asp:ListItem>
<asp:ListItem>Andra Pradesh</asp:ListItem>
<asp:ListItem>Assam</asp:ListItem>
<asp:ListItem>Bihar</asp:ListItem>
<asp:ListItem>Chhattisgarh</asp:ListItem>
<asp:ListItem>Rajasthan</asp:ListItem>
<asp:ListItem>Goa</asp:ListItem>
<asp:ListItem>Gujarat</asp:ListItem>
<asp:ListItem>Haryana</asp:ListItem>
<asp:ListItem>Himachal Pradesh</asp:ListItem>
<asp:ListItem>Jammu and Kashmir</asp:ListItem>
<asp:ListItem>Jharkhand</asp:ListItem>
<asp:ListItem>Karnataka</asp:ListItem>
<asp:ListItem>Kerela</asp:ListItem>
<asp:ListItem>Madhya Pradesh</asp:ListItem>
<asp:ListItem>Maharashtra</asp:ListItem>
<asp:ListItem>Odisa</asp:ListItem>
<asp:ListItem>Sikkim</asp:ListItem>
<asp:ListItem>Punjab</asp:ListItem>
<asp:ListItem>Tamil Nadu</asp:ListItem>
<asp:ListItem>West Bengal</asp:ListItem>
</asp:DropDownList>
</div>
</div>
<div class="col-md-4">
<label>City : </label>
<div class="form-group">
<asp:TextBox Class="form-control" ID="TextBox6" runat="server" Placeholder="City"></asp:TextBox>
</div>
</div>
<div class="col-md-4">
<label>PinCode : </label>
<div class="form-group">
<asp:TextBox CssClass="form-control" ID="TextBox7" runat="server" Placeholder="Pincode" TextMode="Number"></asp:TextBox>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col">
<label>Full Address: </label>
<div class="form-group">
<asp:TextBox CssClass="form-control" ID="TextBox5" runat="server" Placeholder="Full Address" TextMode="MultiLine"></asp:TextBox>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col">
<span class="badge rounded-pill bg-warning text-dark">New Login Credentials</span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6">
<label>Member ID : </label>
<div class="form-group">
<asp:TextBox Class="form-control" ID="TextBox8" runat="server" Placeholder="Member ID"></asp:TextBox>
</div>
</div>
<div class="col-md-6">
<label>Password : </label>
<div class="form-group">
<asp:TextBox CssClass="form-control" ID="TextBox9" runat="server" Placeholder="Password" TextMode="Password"></asp:TextBox>
</div>
</div>
</div>
<div class="row">
<div class="col" style="width:100%;">
<br>
<div class="form-group">
<center>
<%--<asp:Button class="btn btn-success btn-block btn-lg" style="width:510px;" ID="SignUp" runat="server" Text="Sign Up" OnClick="SignUp_Click" />--%>
<asp:Button class="btn btn-success btn-block btn-lg" style="width:510px;" ID="Button1" runat="server" Text="SignUp" OnClick="Button1_Click" />
</center>
</div>
</div>
</div>
</div>
</div>
<< Back To Home
</div>
</div>
</div>
</asp:Content>
Here is my usersignup.aspx.cs file
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
namespace BookManagement
{
public partial class usersignup : System.Web.UI.Page
{
string strcon = WebConfigurationManager.ConnectionStrings["con"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (checkMemberExists())
{
Response.Write("<script>alert('Member Already Exists.Try Again!!!');</script>");
}
else
{
signUpNewMember();
}
}
bool checkMemberExists()
{
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("SELECT * FROM member_master_tabel WHERE member_id='"+TextBox8.Text.Trim()+"';", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count >= 1)
{
return true;
}
else
{
return false;
}
//cmd.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('signup is successful. Go to the login page.');</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
return false;
}
}
void signUpNewMember()
{
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("INSERT INTO member_master_tabel(full_name,dob,contact_no,email,state,city,pincode,full_address,member_id,password,account_status)" +
"VALUES(#full_name,#dob,#contact_no,#email,#state,#city,#pincode,#full_address,#member_id,#password,#account_status)", con);
//SqlCommand cmd = new SqlCommand("INSERT INTO member_master_tabel VALUES('abhay', '11-10-2018', '1234567890', 'mail#demo.com', 'Gujarat', 'Ahmedabad', '380001', 'qwertytjfgnbvf', 'ts13', '456', 'pending');", con);
cmd.Parameters.AddWithValue("#full_name", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#dob", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("#contact_no", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("#email", TextBox4.Text.Trim());
cmd.Parameters.AddWithValue("#state", DropDownList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#city", TextBox6.Text.Trim());
cmd.Parameters.AddWithValue("#pincode", TextBox7.Text.Trim());
cmd.Parameters.AddWithValue("#full_address", TextBox5.Text.Trim());
cmd.Parameters.AddWithValue("#member_id", TextBox8.Text.Trim());
cmd.Parameters.AddWithValue("#password", TextBox9.Text.Trim());
cmd.Parameters.AddWithValue("#account_status", "pending");
cmd.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('signup is successful. Go to the login page.');</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
}
}
Here is my web.config file :
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="con" connectionString="Data Source=PROBOOK-HP\SQLEXPRESS;Initial Catalog=ebookDB;Integerated Security=true" />
</connectionStrings>

How to populate bootstrap modal using c# code?

I created a repeater control which displays data from the database. When the user click delete button it should fetch the respective column data from database and store it in the fields which is actually not happening.
I attached my entire code with this question.
Anyone please help me!
All other solutions available are based on only jQuery. But I want to do it through c#.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Repeater.aspx.cs" Inherits="intern4.Repeater" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="repeaterstylesheet.css" />
</head>
<body>
<form id="form1" runat="server" >
<div>
<asp:Repeater ID="Repeater1" runat="server" >
<HeaderTemplate>
<div class="container align" >
<div class="row header">
<div class="col-sm-2">ID</div>
<div class="col-sm-2">Name</div>
<div class="col-sm-2">Class</div>
<div class="col-sm-2">Edit</div>
<div class="col-sm-2">Delete</div>
</div>
</HeaderTemplate>
<ItemTemplate>
<div class="row data">
<div class="col-sm-2"> <asp:Label ID="lblId" runat="server" Text='<%# Eval("StudentID") %>' /></div>
<div class="col-sm-2"><asp:Label ID="lblName" runat="server" Text='<%# Eval("StudentName") %>' /></div>
<div class="col-sm-2"><asp:Label ID="lblClassx" runat="server" Text='<%# Eval("StudentClass") %>' /></div>
<div class="col-sm-2">Edit</div>
<div class="col-sm-2">
<asp:LinkButton ID="linkbtn" runat="server" ClientIDMode="Static" CssClass="btn btn-primary" data-target="#exampleModalCenter"
data-toggle="modal" CommandArgument='<%# Eval("StudentID") %>' OnCommand="btn_clck" >
Delete
</asp:LinkButton>
</div>
</div>
<hr style="color:blue" />
</ItemTemplate>
<FooterTemplate>
</div>
</FooterTemplate>
</asp:Repeater>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Conformation alert</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<legend class="col-form-label col-sm-2 pt-0">ID</legend>
<div class="col-sm-10">
<div class="form-check">
<asp:label id="lblStudentID" runat="server" class="form-check-label" />
</div>
</div>
</div>
<div class="form-group row">
<label for="inputName" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<asp:TextBox ID="inputName" runat="server" class="form-control" Text=""></asp:TextBox>
</div>
</div>
<div class="form-group row">
<label for="inputClass" class="col-sm-2 col-form-label">Class</label>
<div class="col-sm-10">
<asp:TextBox ID="inputClass" runat="server" class="form-control" Text=""></asp:TextBox>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<asp:Button runat="server" Text="yes" OnClick="Deletestudent" />
</div>
</div>
</div>
</div>
</form>
</body>
</html>
C# code
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace intern4
{
public partial class Repeater : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindRepeater();
}
}
private void BindRepeater()
{
string constr = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT StudentID, StudentName, StudentClass FROM tbl_Student", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
}
}
}
}
protected void Deletestudent(object sender, EventArgs e)
{
int studentId = int.Parse(((sender as Button).NamingContainer.FindControl("lblId") as Label).Text);
string constr = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM tbl_Student WHERE StudentID = #StudentId", con))
{
cmd.Parameters.AddWithValue("#StudentId", studentId);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindRepeater();
}
protected void btn_clck(object sender, CommandEventArgs e)
{
int s = int.Parse((sender as LinkButton).CommandArgument);
lblStudentID.Text = s.ToString();
string constr = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
try
{
SqlCommand cmd = new SqlCommand(
"select * from tbl_Student where StudentID=" + s + "", con);
SqlDataReader sd = cmd.ExecuteReader();
while (sd.Read())
{
inputName.Text = sd.GetValue(1).ToString();
inputClass.Text = sd.GetValue(2).ToString();
}
}
catch (SqlException ex)
{
}
con.Close();
}
}
}
According to this answer you have to add below code after setting the TextBox Controls:
//... Some other code
while (sd.Read()) {
inputName.Text = sd.GetValue(1).ToString();
inputClass.Text = sd.GetValue(2).ToString();
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type='text/javascript'>");
sb.Append("$('#exampleModalCenter').modal('show');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "MyModel",
sb.ToString(), false);
This code will populate the Bootstrap Model from C# code-behind.

Retrieve Textbox value in asp.net ListView

I generating a listview (a list of products for user to make order) with a textbox inside. User may enter quantity of product that want to order in this textbox. I set the initial value of this textbox to 0. My issue is when user insert a new quantity value in this textbox and click submit button, it should retrieve the value that user insert, but it still retrieve the initial value which is 0. Below is my code, can anyone tell me which part of my code is incorrect?
HTML page
<div class="row">
<asp:Listview runat="server" ID="Listview1">
<ItemTemplate>
<div class="col-sm-6 col-md-4 col-lg-4" id="divRow">
<div class="wrap-listview-block">
<div class="listview-block-inner">
<div class="row">
<div class="col-xs-2 col-sm-3 col-md-3 col-lg-3">
<%--<img src="../images/img-product-gerbang-jingga.jpg">--%>
<telerik:RadBinaryImage runat="server" ID="RadBinaryImage1" DataValue='<%#Eval("ProductImg") %>' Width="80.02" Height="109.55"
AutoAdjustImageControlSize="false" ToolTip='<%#Eval("ProdCode", "Photo of {0}") %>'
AlternateText='<%#Eval("ProdCode", "Photo of {0}") %>' />
</div>
<div class="col-xs-10 col-sm-9 col-md-9 col-lg-9 listing-right">
<div class="caption">
<h3>(<%#Eval("ProdCode")%>) <%#Eval("ProdName")%> </h3>
<div class="btn-details">
<i class="fa fa-info-circle" aria-hidden="true"></i> <i class="fa fa-gift" aria-hidden="true"></i> <i class="fa fa-file-image-o" aria-hidden="true"></i> <i class="fa fa-book" aria-hidden="true"></i>
</div>
<div class="btn-details">
<form class="form-inline">
<%--<select class="form-control input-sm col-xs-6">
<option>Carton</option>
<option>Piece</option>
</select>--%>
<asp:DropDownList ID="ddlQuantity" runat="server" CssClass="form-control input-sm col-xs-6">
<asp:ListItem Value="1" Selected="True">Carton</asp:ListItem>
<asp:ListItem Value="2">Piece</asp:ListItem>
</asp:DropDownList>
<div class="input-group col-xs-6">
<span class="input-group-btn">
<asp:LinkButton runat="server" CssClass="btn btn-sm btn-sub" ID="btnDown"><i class="fa fa-minus" aria-hidden="true"></i></asp:LinkButton>
</span>
<asp:TextBox runat="server" ID="txtQuantity" CssClass="form-control input-sm text-right" Text="0" Width="90"></asp:TextBox>
<span class="input-group-btn">
<asp:LinkButton runat="server" CssClass="btn btn-sm btn-sub" ID="btnUp"><i class="fa fa-plus" aria-hidden="true"></i></asp:LinkButton>
</span>
<ajaxToolkit:NumericUpDownExtender ID="NumericUpDownExtender1" Runat="server" TargetControlID="txtQuantity" TargetButtonDownID="btnDown" TargetButtonUpID="btnUp"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div><!-- listing block -->
</div><!--Product block -->
</ItemTemplate>
</asp:Listview>
</div>
<div class="footer-bar">
<div class="row">
<div class="col-xs-12">
<asp:LinkButton runat="server" ID="btnProceedOrder" OnClick="btnProceedOrder_Click" >
<div class="footer-inner">
<span class='glyphicon glyphicon-shopping-cart' aria-hidden="true"></span>
<br />
<asp:Literal runat="server" ID="litProceedOrder" Text="<%$ Resources:Lang, ProceedOrder %>"></asp:Literal>
</div>
</asp:LinkButton>
</div>
</div>
</div>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
String UserName = Utils.Session.Get(Constants.SessionObjects.UserName);
if (!IsPostBack)
{
DataTable dt = this.GetData();
Listview1.DataSource = dt;
Listview1.DataBind();
}
}
private DataTable GetData()
{
string RetailLink = ConfigurationManager.ConnectionStrings["DefaultDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(RetailLink))
{
using (SqlCommand cmd = new SqlCommand("EXEC sp_mProduct_Sel_ByPrincipalRetailer#PWA " + UserName + ", " + PricipalID.ToInt32()))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void btnProceedOrder_Click(object sender, EventArgs e)
{
foreach (ListViewDataItem row in Listview1.Items)
{
TextBox txtQuantity = row.FindControl("txtQuantity") as TextBox;
string Quantity = txtQuantity.Text.ToString(); //string Quantity keep getting "0", I need to get the value that user insert.
}
}

Cannot implicitly convert type 'string' to 'System.Web.UI.WebControls.TextBox' Error

I'm getting this error, but I just can't tell where it might be coming from. The line that the error page is referencing is:
# Page Title="" Language="C#" MasterPageFile="~/CV.Master" AutoEventWireup="true" CodeBehind="AddPost.aspx.cs" Inherits="CV_Blog_WDW.AddPost"
But I can't see how that line can cause that error? Unless there's something I'm missing?
My .aspx code is:
<%# Page Title="" Language="C#" MasterPageFile="~/CV.Master" AutoEventWireup="true" CodeBehind="AddPost.aspx.cs" Inherits="CV_Blog_WDW.AddPost" %>
<asp:Content ID="Content1"
ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
<!-- =========
Special Nav for BLog page
===================================-->
<nav class="nav-blog">
<a href="default.aspx"
class="btn btn-left"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Home">
<i class="fa fa-home"></i>
</a>
<a href="#"
class="btn btn-big-blog">Blog</a>
<a href="#"
class="btn btn-right"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Reload Page">
<i class="fa fa-refresh"></i>
</a>
</nav>
<!-- =========
Start Show Yor Name Section
===================================-->
</div>
</header>
<!-- =========
End portrait section
===================================-->
<!-- =========
Start Content section
===================================-->
<section class="content open"
id="main-content">
<div class="body-content"
id="blog">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="blog-posts">
<div class="blog-post">
<h3 class="title with-icon">
<span class="fa fa-comment-o icn-title"></span> Add A Post
</h3>
<div class="box-block">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Title">Title</label>
<asp:TextBox ID="Title"
runat="server"
CssClass="form-control"></asp:TextBox>
</div>
<div class="form-group">
<label for="FeaturedImage">Featured Image</label>
<asp:FileUpload ID="FeaturedImage"
runat="server"
CssClass="form-control" />
</div>
</div>
</div>
<div class="form-group">
<label for="MesageForm">Body</label>
<asp:TextBox ID="Body"
TextMode="MultiLine"
Rows="8"
runat="server"
CssClass="form-control"></asp:TextBox>
</div>
<asp:Button id="btnAdd"
runat="server"
CssClass="btn btn-flat btn-lg"
Text="Add Post"
OnClick="btnAdd_Click" />
</div>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
And my code behind is:
public partial class AddPost : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if(FeaturedImage.HasFile)
{
try
{
string filename = Path.GetFileName(FeaturedImage.FileName);
FeaturedImage.SaveAs(Server.MapPath("~/assets/images/blog/") + filename);
}
catch(Exception ex)
{
string error = ex.Message;
}
}
try
{
string connection = WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("AddPost", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", Title.Text);
cmd.Parameters.AddWithValue("#Date", DateTime.Now);
cmd.Parameters.AddWithValue("#FeatureImage", Path.GetFileName(FeaturedImage.FileName));
cmd.Parameters.AddWithValue("#PostedBy", 1);
cmd.Parameters.AddWithValue("#Body", Body.Text);
con.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
}
}
}
I've google'ed the error but there's nothing that seems relevant to my code? Really stumped on this one, not been able to try any fixes as to be honest not sure where to start. As far as I can see I'm not making a conversion, but maybe there's one going on that I'm, not aware of?
The error comes from assigning a string to a TextBox variable. The usual reason is that one forgets the Text property, and use something like:
MyTextbox = "Some string";
intead of:
MyTextbox.Text = "Some string";
However, as there is no such code in your methods, and because the error message points to the aspx page, the error is somewhere in the code that is generated from the markup.
You have a text box named Title. There is already a string property by that name in the Page class, and when the generated code tries to set the string property, the assigment will use the TextBox field instead as it shadows the string property.
Rename the Title text box to something that isn't used already.

Selected Index Changed event not firing both Autopostback property

In my Dropdownlist Selected index change event not firing.Here i use auto post back true &
View state also true.But Selected Index Changed Event not firing
My Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AdminEagleViewLogin.aspx.cs" Inherits="AdminEagleViewLogin" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style>
body{padding-top:20px;}
</style>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<div class="row">
User : <asp:DropDownList ID="drpusr" runat="server" Visible="true" OnSelectedIndexChanged="drpusr_SelectedIndexChanged" AutoPostBack="true" EnableViewState="true" ></asp:DropDownList>
Password: <asp:Label ID="lbluserpw" runat="server"></asp:Label>
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Please sign in</h3>
</div>
<div class="panel-body">
<form accept-charset="UTF-8" role="form">
<fieldset>
<div class="form-group">
<asp:TextBox ID="txtusr" runat="server"></asp:TextBox>
</div>
<div class="form-group">
<asp:TextBox ID="txtpw" runat="server" TextMode="Password"></asp:TextBox>
</div>
<div class="checkbox">
<label>
<input name="remember" type="checkbox" value="Remember Me"> Remember Me
</label>
</div>
<asp:CheckBox ID="chkremember" runat="server" Visible="false" class="remchkbox" />
<asp:Button ID="submit" runat="server" class="btn btn-lg btn-success btn-block" Text="Submit" OnClick="submit_Click" />
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
ServerSide
User bind to Dropdown is working.
public partial class AdminEagleViewLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
BindUsers();
//lbluserpw.Text = Membership.Provider.GetPassword(drpusr.SelectedValue, String.Empty);
}
protected void submit_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(txtusr.Text, txtpw.Text))
{
FormsAuthentication.SetAuthCookie(txtusr.Text, chkremember.Checked);
string[] CurrentUserRole = Roles.GetRolesForUser(txtusr.Text);
var admin = "Administrator";
var manager = "Manager";
var user = "User";
if (CurrentUserRole.Contains(admin))
{
Response.Redirect("Administrator.aspx");
}
else if (CurrentUserRole.Contains(manager))
{
Response.Redirect("Manager.aspx");
}
else
{
Response.Redirect("UserPage.aspx");
}
}
else
{
Response.Redirect("AdminEagleViewLogin.aspx");
}
}
protected void BindUsers()
{
DataAccess da = new DataAccess();
drpusr.DataSource = da.GetUsers();
drpusr.DataTextField = "UserName";
drpusr.DataValueField = "UserId";
drpusr.DataBind();
drpusr.Items.Insert(0, new ListItem("-- Select User --", "0"));
drpusr.Items.RemoveAt(1);
}
protected void drpusr_SelectedIndexChanged(object sender, EventArgs e)
{
lbluserpw.Text = Membership.Provider.GetPassword(drpusr.SelectedValue, String.Empty);
}
}
Try this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindUsers();
}
}
You shouldn't put a form element inside another form:
<form accept-charset="UTF-8" role="form">
<fieldset>
...
<asp:Button ID="submit" runat="server" class="btn btn-lg btn-success btn-block" Text="Submit" OnClick="submit_Click" />
</fieldset>
</form>
remove the inner form.
[Update]
Another problem is the "ID" property of the button.
change it to something else, other than "submit".

Categories

Resources