Contact form send even if the field(s) are empty - asp.net

Please help...
I just got the below code from the internet and don't know how to fix the issue.
Issue is:- even if the form is empty or one of the fields is empty, I still receive the email.
I think I need to add some validation here but I don't know how. I am not a programmer and new to asp.
Here is the code.
the ASPX is:
<%# Page Language="C#" AutoEventWireup="true" ValidateRequest = "false" CodeFile="contact.aspx.cs" Inherits="_Default" %>
<html>
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<div class="inp_title"><asp:Label ID="Label1" runat="server" Text="Name*" /></div>
<div>
<asp:TextBox ID="txtName" runat="server" ValidationGroup = "contact" CssClass="inp_h" /><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter your name." ControlToValidate = "txtName" Display="Dynamic" /></div>
<div class="inp_title"><asp:Label ID="Label2" runat="server" Text="Subject*" /></div>
<div>
<asp:TextBox ID="txtSubject" runat="server" /><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*" ControlToValidate = "txtSubject" Display="Dynamic" /></div>
<div class="inp_title"><asp:Label ID="Label3" runat="server" Text="Email Address*" /></div>
<div>
<asp:TextBox ID="txtEmail" runat="server" CssClass="inp_h" Display="Dynamic" /><br />
<asp:RegularExpressionValidator id="valRegEx" runat="server" ControlToValidate="txtEmail" ValidationExpression=".*#.*\..*" ErrorMessage="Please enter a valid email address." Display="Dynamic" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Please enter your email address." ControlToValidate = "txtEmail" />
</div>
<div class="inp_title-2"><asp:Label ID="Label4" runat="server" Text="Message*" /></div>
<div>
<asp:TextBox ID="txtBody" runat="server" TextMode = "MultiLine" CssClass="inp_h" Display="Dynamic" /><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Please enter your message." ControlToValidate = "txtBody" />
</div>
<div class="inp_h"><asp:FileUpload ID="FileUpload1" runat="server" /></div>
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" CssClass="form-buttons"/>
<asp:Label ID="lblMessage" runat="server" Text="" ForeColor = "Green" />
</form>
</body>
</html>
The code-behind is :
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
MailMessage mm = new MailMessage("email1#domain.com", "email2#domain.com");
mm.Subject = txtSubject.Text;
mm.Body = "Name: " + txtName.Text + "<br /><br />Email: " + txtEmail.Text + "<br /><br />Message:<br />" + txtBody.Text;
if (FileUpload1.HasFile)
{
string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName) ;
mm.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.office365.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "email1#domain.com";
NetworkCred.Password = "emai1password";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
lblMessage.Text = "Email Sent Sucessfully.";
}
}

Here you go, this will not send the email if the fields have not been filled out if you're not using validation - otherwise just add 'causesvalidation=true' to your submit button as per the earlier answer
protected void btnSend_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(txtName.Text) && !string.IsNullOrWhiteSpace(txtEmail.Text) && !string.IsNullOrWhiteSpace(txtBody.Text) )
{
MailMessage mm = new MailMessage("email1#domain.com", "email2#domain.com");
mm.Subject = txtSubject.Text;
mm.Body = "Name: " + txtName.Text + "<br /><br />Email: " + txtEmail.Text + "<br /><br />Message:<br />" + txtBody.Text;
if (FileUpload1.HasFile)
{
string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName) ;
mm.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.office365.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "email1#domain.com";
NetworkCred.Password = "emai1password";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
lblMessage.Text = "Email Sent Sucessfully.";
}
else
{
lblMessage.Text = "You need to fill in the fields.";
}
}

your problem is here :
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" CssClass="form-buttons"/>
use this instead : CausesValidation="true" in your button. This will validate your required field before post event is fired.
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" CssClass="form-buttons" CausesValidation="true"/>

You need to have a required field validator for the textbox

just use
CausesValidation="true"
inside your button control, this will validate your controls client side.
Like I said :
<asp:Button ... CausesValidation="true"/>
or you can validate it at server side too.

Related

Create a dropdown that filters the output of my repeater

I have a repeater that lists all the products in my Products table and I need a dropdown box to filter the repeater content by category_id. I have absolutely no idea what I'm doing. Here is my repeater:
<asp:Repeater ID="RShopItems" runat="server" ItemType="WebDevAssessment.Models.Product">
<ItemTemplate>
<div class="col-md-4 productOuterContainer">
<div class="col-md-10 col-md-offset-1 productInnerContainer border">
<a href='<%#"ProductDetails.aspx?item=" + Item.product_id %>' runat="server" target="_parent">
<img runat="server" alt='<%# Item.product_name %>' src='<%# Item.product_image1 %>'
style="width: 100%" class="img-thumbnail" />
</a>
<h4 class="text-center"><%# Item.product_name %></h4>
<p class="text-center">Size: <%#Item.product_size%> - $<%#Item.product_price%></p>
<p class="features_text text-center"><%#Item.product_feat_short%></p>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
And the behind code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebDevAssessment.Models;
namespace WebDevAssessment
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (WebDatabaseEntities wde = new WebDatabaseEntities())
{
var products = (from si in wde.Products
orderby si.product_price descending
select si).ToList();
// assign the data to the repeater
RShopItems.DataSource = products;
// trigger the repeater to incorporate to display the data
RShopItems.DataBind();
}
}
}
}
Ok, you can use this apporach.
In this example, we have a repeater - showing hotel names.
We have a drop down list to filter by city (no choice = all cities).
So, the mark up looks like this:
<asp:DropDownList ID="DropDownList1" runat="server" DataTextField="City" DataValueField="ID" AutoPostBack="True">
</asp:DropDownList>
<br />
<br />
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="border-style:solid;color:black;width:250px;float:left">
<div style="padding:5px;text-align:right">
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" Text ='<%# Eval("HotelName") %>' Width="130px" />
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" Text ='<%# Eval("FirstName") %>' Width="130px" />
<br />
Last Name: <asp:TextBox ID="txtLast" runat="server" Text ='<%# Eval("LastName") %>' Width="130px" />
<br />
City: <asp:TextBox ID="txtCity" runat="server" Text ='<%# Eval("City") %>' Width="130px" />
<br />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
And the code to load up drop, load up Repeater, and filter looks like this:
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
{
LoadDropDown();
LoadGrid();
}
}
public void LoadDropDown()
{
// load drop down list
using (SqlCommand cmdSQL = new SqlCommand("SELECT ID, City from tblCity ORDER BY City",
new SqlConnection(My.Settings.TEST3)))
{
cmdSQL.Connection.Open();
DropDownList1.DataSource = cmdSQL.ExecuteReader;
DropDownList1.DataBind();
// add blank row choice to drop down list
DropDownList1.Items.Insert(0, new ListItem(string.Empty, string.Empty));
}
}
public void LoadGrid(string sFilter = "")
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM tblHotels",
new SqlConnection(My.Settings.TEST3)))
{
if (sFilter != "")
{
cmdSQL.CommandText += " WHERE City = #City";
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = DropDownList1.SelectedItem.Text;
}
cmdSQL.CommandText += " ORDER BY HotelName";
cmdSQL.Connection.Open();
Repeater1.DataSource = cmdSQL.ExecuteReader;
Repeater1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
LoadGrid(DropDownList1.SelectedItem.Text);
}
So it now looks like this:
So, on first load - you load up the dropdown, and the repeater.
Dropdown list has auto post back = true, and it simply filters the Repeater by applying a parameters (optional) to the data source for the repeater.
It not a lot of code, and I don't see any advantages to using linq as you are.

how to store data into database using text-area

How to store data in the database.
it will show the following exception
Additional information: Procedure or function 'spUploadImage' expects parameter '#detail', which was not supplied.
Following is the Movies.aspx file contents :
<html>
<head>
<script>
var maxAmount = 250;
function textCounter(textField, showCountField) {
if (textField.value.length > maxAmount) {
textField.value = textField.value.substring(0, maxAmount);
} else {
showCountField.value = maxAmount - textField.value.length;
}
}
</script>
</head>
<body>
<center>
<asp:Label ID="label3" Text="Name of Movie: " runat="server"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /><br />
<asp:Label ID="label4" Text="Details of Movie: " runat="server"></asp:Label><br />
<textarea id="txtCommentBox" name="txtCommentBox" rows="6" style="width:340px;" onKeyDown="textCounter(this.form.txtCommentBox,this.form.countDisplay);" onKeyUp="textCounter(this.form.txtCommentBox,this.form.countDisplay);"></textarea>
<br />
<input readonly type="text" name="countDisplay" size="3" maxlength="3" value="250"> Characters Remaining
<br />
<br />
<asp:Label ID="label2" Text="Select Image of Movie: " runat="server"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:HyperLink ID="HyperLink1" runat="server">View Uploaded Image</asp:HyperLink>
</center>
</body>
</html>
</asp:Content>
Following is the Movies.aspx.cs file contents :
public partial class Movies : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Label1.Visible = false;
HyperLink1.Visible = false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string txt = TextBox1.Text;
string text = Request.Form["txtCommentBox_1"];
HttpPostedFile postedFile= FileUpload1.PostedFile;
string fileName = Path.GetFileName(postedFile.FileName);
string fileExtension = Path.GetExtension(fileName);
int fileSize = postedFile.ContentLength;
if(fileExtension.ToLower()==".jpg" || fileExtension.ToLower()==".png" || fileExtension.ToLower()==".bmp" || fileExtension.ToLower()==".gif")
{
Stream stream= postedFile.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con=new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spUploadImage",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramName = new SqlParameter()
{
ParameterName = "#Name",
Value = fileName
};
cmd.Parameters.Add(paramName);
SqlParameter paramSize = new SqlParameter()
{
ParameterName = "#Size",
Value = fileSize
};
cmd.Parameters.Add(paramSize);
SqlParameter parammName = new SqlParameter()
{
ParameterName = "#mName",
Value = txt
};
cmd.Parameters.Add(parammName);
SqlParameter paramImageData = new SqlParameter()
{
ParameterName = "#ImageData",
Value = bytes
};
cmd.Parameters.Add(paramImageData);
SqlParameter paramdetail = new SqlParameter()
{
ParameterName = "#detail",
Value = text
};
cmd.Parameters.Add(paramdetail);
SqlParameter paramNewId = new SqlParameter()
{
ParameterName = "#NewId",
Value = -1,
Direction=ParameterDirection.Output
};
cmd.Parameters.Add(paramNewId);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Upload Successful";
Label1.ForeColor = System.Drawing.Color.Green;
HyperLink1.Visible = true;
HyperLink1.NavigateUrl = "~/Moviesimg.aspx?Id="+cmd.Parameters["#NewId"].Value.ToString();
}
}
else
{
Label1.Visible = true;
Label1.Text = "Only Images (.jpg, .png, .gif and .bmp) can be uploaded...";
Label1.ForeColor = System.Drawing.Color.Red;
HyperLink1.Visible = false;
}
}
}
and the stored procedure is as follows :
create proc spUploadImage
#Name nvarchar(255),
#Size int,
#ImageData varbinary(max),
#mName nvarchar(50),
#detail nvarchar(300),
#NewId int output
as
Begin
Insert into tblImages
values(#Name,#Size,#mName,#detail,#ImageData)
select #NewId = SCOPE_IDENTITY()
End
But I want to get a text from the text area and to store in the database.
but it raises an exception...
You are missing a form tag. Use an ASP control instead of a plain HTML control - all the other controls are ASP so be consistent.
<html>
<body>
<form id="form1" runat="server">
<asp:TextBox id="txtImagename1" TextMode="multiline" Columns="50"
Rows="1" runat="server" />
</form>
</body>
</html>
protected void Button1_Click(object sender, EventArgs e)
{
string text = Server.HtmlEncode(txtImagename1.Text);
...
}
The Request.Form collection cannot be used if your form is over 100 KB:
msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx
If you are setting runat="server" to any control, in that case the control must be placed inside a form tag with runat="server" like following
<html>
<body>
<form id="form1" runat="server">
<center>
<textarea id="txtImagename1" name="txtImagename1" runat="server" rows="1" cols="50">
</textarea>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:HyperLink ID="HyperLink1" runat="server">View Uploaded Image</asp:HyperLink>
</center>
</form>
</body>
</html>
To access this on server side you can simply use the the InnerText property of the TextArea as following.
txtImagename1.InnerText
If you want you can also access it using Form object also as following.
Request.Form["txtImagename1"]
For this the control can be simple TextArea without runat attribute.

How can I retrieve the ex Exception object from session state and display the Message property of the exception?

ERROR.ASPX.CS page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace XEx21HandleErrors
{
public partial class Error : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblError.Text = ex.Message;
}
}
}
ERROR.ASPX
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Error.aspx.cs" Inherits="XEx21HandleErrors.Error" %>
<asp:Content ContentPlaceHolderID="mainPlaceholder" runat="server">
<h1 class="text-danger">An error has occurred</h1>
<div class="alert alert-danger">
<p><asp:Label ID="lblError" runat="server"></asp:Label></p>
</div>
<asp:Button ID="btnReturn" runat="server" Text="Return to Order Page"
PostBackUrl="~/Order.aspx" CssClass="btn btn-danger" />
</asp:Content>
CONFIRMATION.ASPX.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
namespace XEx21HandleErrors
{
public partial class Confirmation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var customer = (Customer)Session["Customer"];
var date = DateTime.Today.AddDays(1).ToShortDateString();
var text = $"Thank you for your order, {customer.FirstName}! It will be shipped on {date}.";
lblConfirm.Text = text;
SendConfirmation(customer, text);
}
private void SendConfirmation(Customer customer, string body)
{
try
{
MailMessage msg = new MailMessage("halloween#murach.com", customer.EmailAddress);
msg.Subject = "Order Confirmation";
msg.Body = body;
string html = "<html><head><title>Order Confirmation</title></head>"
+ "<body><h3>Thanks for your order!</h3>"
+ "<p>" + body + "</p></body></html>";
AlternateView view = AlternateView.CreateAlternateViewFromString(html, null, "text/html");
msg.AlternateViews.Add(view);
SmtpClient client = new SmtpClient("localhost");
client.Send(msg);
}
catch (Exception ex)
{
Session["Exception"] = ex;
Response.Redirect("~/Error.aspx");
}
}
}
}
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Order.aspx.cs" Inherits="XEx21HandleErrors.Order" %>
<asp:Content ID="mainContent" ContentPlaceHolderID="mainPlaceholder" runat="server">
<div class="row"><%-- row 1 --%>
<div class="col-sm-8"><%-- product drop down and info column --%>
<div class="form-group">
<label class="col-sm-6">Please select a product:</label>
<div class="col-sm-6">
<asp:DropDownList ID="ddlProducts" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource1" DataTextField="Name"
DataValueField="ProductID" CssClass="form-control">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString='<%$ ConnectionStrings:HalloweenConnection %>'
SelectCommand="SELECT [ProductID], [Name], [ShortDescription],
[LongDescription], [ImageFile], [UnitPrice] FROM [Products]
ORDER BY [Name]">
</asp:SqlDataSource>
</div>
</div>
<div class="form-group">
<div class="col-sm-12"><h4><asp:Label ID="lblName" runat="server"></asp:Label></h4></div></div>
<div class="form-group">
<div class="col-sm-12"><asp:Label ID="lblShortDescription" runat="server"></asp:Label></div></div>
<div class="form-group">
<div class="col-sm-12"><asp:Label ID="lblLongDescription" runat="server"></asp:Label></div></div>
<div class="form-group">
<div class="col-sm-12"><asp:Label ID="lblUnitPrice" runat="server"></asp:Label></div></div>
</div>
<div class="col-sm-4"><%-- product image column --%>
<asp:Image ID="imgProduct" runat="server" />
</div>
</div><%-- end of row 1 --%>
<div class="row"><%-- row 2 --%>
<div class="col-sm-12">
<div class="form-group">
<label class="col-sm-2">Quantity:</label>
<div class="col-sm-3">
<asp:TextBox ID="txtQuantity" runat="server"
CssClass="form-control"></asp:TextBox></div>
<div class="col-sm-7">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" CssClass="text-danger"
runat="server" ControlToValidate="txtQuantity" Display="Dynamic"
ErrorMessage="Quantity is a required field."></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" runat="server" CssClass="text-danger"
ControlToValidate="txtQuantity" Display="Dynamic"
ErrorMessage="Quantity must range from 1 to 500."
MaximumValue="500" MinimumValue="1" Type="Integer"></asp:RangeValidator></div>
</div>
<div class="form-group">
<div class="col-sm-12">
<asp:Button ID="btnAdd" runat="server" Text="Add to Cart"
onclick="btnAdd_Click" CssClass="btn" />
<asp:Button ID="btnCart" runat="server" Text="Go to Cart"
PostBackUrl="~/Cart.aspx" CausesValidation="False" CssClass="btn" />
<asp:Button ID="btnCheckOut" runat="server" Text="Check Out"
PostBackUrl="~/CheckOut1.aspx" CausesValidation="False" CssClass="btn" />
</div>
</div>
</div>
</div><%-- end of row 2 --%>
</asp:Content>
Hello Everyone,
I am working on an application in which I want to display an exception error message when a user enters a email like this: email inside of the email textbox, but the problem that I am having is I am confused about how I can retrieve the ex Exception object from  session state and display the Message property of the exception in the label on the Error page. Here are some of my web application pages. I am trying to do this in the Error.aspx.cs (or code behind file). Do anyone think they can help?
Use try catch in those pages/events.
try {
//Do stuffs here such as pageload, click events and so on...
}
catch(Exception ex)
{
Session["ErrorMsg"] = ex.Message;
Response.Redirect("~/Error.aspx");
}
In Error.aspx
protected void Page_Load(object sender, EventArgs e)
{
lblError.Text = Session["ErrorMsg"] == null ? "" : Session["ErrorMsg"].ToString();
}

DropDownList SelectIndexChanged not working?

This seems to be a common problem. I have tried different solutions but its still not working. This is my code.
HTML:
<div class="form-group">
<label for="exampleInputEmail1">Artist *</label>
<asp:DropDownList ID="artistDropdown" runat="server" CssClass="form-control" AutoPostBack="True" OnSelectedIndexChanged="artistDropdown_SelectedIndexChanged" ViewStateMode="Enabled"></asp:DropDownList>
<asp:TextBox ID="mytest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="artistDropdown" SetFocusOnError="true" ErrorMessage="Required Field" Font-Bold="True" Font-Names="Arial" Font-Size="X-Small" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:Label ID="lblMessage" runat="server" CssClass="help-block" Visible="False">Cant select Artist with no Manager</asp:Label>
</div>
Function: OnSelectedIndexChanged
protected void artistDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedArtist = artistDropdown.SelectedValue;
mytest.Text = selectedArtist;
string query = "Select [Manager ID] from Artist Where ID = '" + selectedArtist + "'";
string myConnection = dbController.connectionString;
SqlConnection conn = new SqlConnection(myConnection);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
object obj = cmd.ExecuteScalar();
if (obj is System.DBNull)
{
artistDropdown.SelectedValue = "";
lblMessage.Visible = true;
}
else
{
lblMessage.Visible = false;
}
conn.Close();
}
I am loading DropDownList in Page_Load() function and AutoPostBack="True" is set for DropDownList.
I have also made a TextBox which is being set to the selectedValue from DropDownList to check if on OnSelectedIndexChanged is firing. But text box remains empty.
What am I doing wrong?
Did you put the binding of your dropdown in the if (!postback) {} ?
If you rebind the list after every postback, you get the value of the first list item when you reach the artistDropdown_SelectedIndexChanged event.
If this item has an empty string value...

Why Image is not attached from database with AsyncFileUpload control in asp.net?

I am working with ajax AsyncFileUpload control. I have requirement where when user click on fileuploader and select the file from picture and immediately the picture will display on my image control I am using the following method
protected void fileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string imagepath = Server.MapPath("~/Pics/");
string serverfilename = Path.GetFileName(AsyncFileUpload1.PostedFile.FileName);
string fullpath = Path.Combine(imagepath, serverfilename);
string path = "~/Pics/" + serverfilename;
//string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
//string path = Server.MapPath("~/Pics/") + filename;
AsyncFileUpload1.SaveAs(fullpath);
// FileUpload1.PostedFile.SaveAs(path);
SqlCommand cmd = new SqlCommand("insert findfriend values('" + path + "','" + TextBox1.Text + "')", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
SqlCommand GetImage = new SqlCommand("select * from findfriend where name='" + TextBox1.Text + "'", con);
GetImage.CommandType = CommandType.Text;
SqlDataReader dr = GetImage.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
Image1.ImageUrl = dr["picture"].ToString();
}
}
My aspx source
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
// This function will execute after file uploaded successfully
function uploadComplete() {
document.getElementById('<%=lblMsg.ClientID %>').innerHTML = "File Uploaded Successfully";
}
// This function will execute if file upload fails
function uploadError() {
document.getElementById('<%=lblMsg.ClientID %>').innerHTML = "File upload Failed.";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<ajax:ToolkitScriptManager ID="scriptManager1" runat="server"/>
Your Name:
<asp:TextBox ID="TextBox1" runat="server" Width="223px"></asp:TextBox>
<br />
<br />
Upload Picture:<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<ajax:AsyncFileUpload ID="AsyncFileUpload1" OnClientUploadComplete="uploadComplete" OnClientUploadError="uploadError"
CompleteBackColor="White" Width="350px" runat="server" UploaderStyle="Modern" UploadingBackColor="#CCFFFF"
ThrobberID="imgLoad" OnUploadedComplete="fileUploadComplete" />
<asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:Image ID="Image1" runat="server" Height="295px" Width="338px" />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Button" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Now the problem is this that my picture path is saving into database succesfully image is not binding with image control Experts tell me please where i am wrong
This is because you are trying to access full path i.e. Path from root level like C:/Folder1/Folder2; Which doesn't work in case of Website.
I am assuming Pic folder in Solution folder.
So path have to be something like
Image1.ImageUrl = #"Pic\logo.jpg";
Pic\logo.jpg"
is the value coming from your Database
You don't need to use absolute path using ~

Resources