I want to show image in image control on page load. I'm using the following code. My problem is that the image is saved in the database as binary data, but I can't retrieve the image in the image control
public partial class TeacherProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
profilepic();
}
protected void upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
HttpPostedFile file = FileUpload1.PostedFile;
Byte[] imgbyte = new Byte[file.ContentLength];
file.InputStream.Read(imgbyte, 0, file.ContentLength);
SqlCommand cmd = new SqlCommand("Update Registration set Photo = '" + imgbyte + "' where id ='" + idd.Text + "' ", con);
//cmd.Parameters.AddWithValue("#userid", 222); //image id
//cmd.Parameters.AddWithValue("#pic", imgbyte);
//try
//{
con.Close();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Image Uploaded";
con.Close();
//}
//catch
//{
// Label1.Text = "Try Again";
//}
}
}
public void profilepic()
{
SqlCommand cmd2 = new SqlCommand("select Photo from Registration where Username = '" + username1.Text + "'", con);
//cmd2.Parameters.AddWithValue("#userid", username1.Text);
con.Open();
SqlDataReader dr = cmd2.ExecuteReader();
if (dr.Read())
{
byte[] bytes = (byte[])dr["Photo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/png;base64," + base64String;
cmd2.ExecuteNonQuery();
con.Close();
}
else
{
}
}
}
Can anybody help me please?
Thanks in advance...
my code for file upload
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="fileUpload.aspx.cs" Inherits="fetchImage.fileUpload" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
margin-left: 0px;
}
.auto-style2 {
margin-left: 6px;
margin-top: 0px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<div>
<asp:TextBox ID="TextBox1" runat="server" CssClass="auto- style1"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CssClass="auto-style2" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
file upload cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace fetchImage
{
public partial class fileUpload : System.Web.UI.Page
{
string path;
SqlConnection con = new SqlConnection("Data Source=DESKTOP- U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs(Request.PhysicalApplicationPath + "/Images/"+ FileUpload1.FileName.ToString());
path = "Images/"+FileUpload1.FileName.ToString();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Images values('"+path.ToString()+"','"+TextBox1.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
}
}
}
for showing the file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ShowImage.aspx.cs" Inherits="fetchImage.ShowImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<table>
<tr>
<td>
<img src="<%#Eval("image_path") %>" height="100" width="100" />
<td><%#Eval("title") %></td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
file show cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace fetchImage
{
public partial class ShowImage : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP- U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Images";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
con.Close();
}
}
}
please create a table before proceeding
create table Images(image_path varchar(MAX), title varchar(50));
and lastly add a folder Images in your project by right clicking at your project name
Related
I am using ASP.NET and SQL Server to send email to multiple recipients with loop. But there is an error here. I have find my solution from internet but still can't solve it.
Here is the error shown:
var toAddress = mm.To.Add(email);
Here is my .aspx file code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="push_notification_admin.aspx.cs" Inherits="Assignment.push_notification_admin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function alertme() {
Swal.fire(
"The Email Successfully Sent!" ,
'success'
)
}
</script>
<style>
.error {
color: red;
background-image: url("../images/error.png");
background-repeat: no-repeat;
padding-left: 20px;
font-size: 12px;
}
.auto-style1 {
height: 33px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Push Notification:</h2>
<div>
<table style="width: 100%;">
<tr>
<td> <asp:Label ID="Label2" runat="server" Text="Subject"></asp:Label></td>
<td> <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter subjuct!" ControlToValidate="TextBox1" CssClass="error" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style1"><asp:Label ID="Label1" runat="server" Text="Content"></asp:Label></td>
<td class="auto-style1"><asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter content!" ControlToValidate="TextBox2" CssClass="error" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /></td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
Here is my aspx.cs file code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net.Configuration;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
using System.Collections;
using System.Net.Security;
namespace Assignment
{
public partial class push_notification_admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * from Notification", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
ArrayList emailArray = new ArrayList();
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
while (reader.Read()){
emailArray.Add(reader["Notice_email"]);
}
foreach (string email in emailArray) {
using (MailMessage mm = new MailMessage(smtpSection.From, "sender#gmail.com"))
{
// Gmail Address from where you send the mail
var fromAddress = "inpuzzle2021#gmail.com";
// any address where the email will be sending
var toAddress = mm.To.Add(email);
//Password of your gmail address
const string fromPassword = "inpuzzlepwd";
// Passing the values and make a email formate to display
string subject = TextBox1.Text.ToString();
string body = TextBox2.Text.ToString();
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
}
reader.Close();
con.Close();
}
}
}
I will be appreciate if someone could help me to solve this problem.
Add method of mm.To is void. i.e. the method returns nothing and hence you cannot assign it to a variable. so your code should be just mm.To.Add(email);. This should fix the error you see.
Here is the latest coding and I have solve it!
The coding that I change to fix it are:
emailArray.Add(reader["Notice_email"].ToString());
and
var toAddress = email;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net.Configuration;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
using System.Collections;
using System.Net.Security;
namespace Assignment
{
public partial class push_notification_admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * from Notification", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
ArrayList emailArray = new ArrayList();
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
while (reader.Read()){
emailArray.Add(reader["Notice_email"].ToString());
}
foreach (string email in emailArray) {
using (MailMessage mm = new MailMessage(smtpSection.From, "sender#gmail.com"))
{
// Gmail Address from where you send the mail
var fromAddress = "inpuzzle2021#gmail.com";
// any address where the email will be sending
var toAddress = email;
//Password of your gmail address
const string fromPassword = "inpuzzlepwd";
// Passing the values and make a email formate to display
string subject = TextBox1.Text.ToString();
string body = TextBox2.Text.ToString();
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
}
reader.Close();
con.Close();
}
}
}
i have this method in mail.cs file which take one parameter,call store procedures and and return values from database.
public void select(string type)
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("EmailSetup_CRUD"))
{
cmd.Parameters.AddWithValue("#Action", "SELECT");
cmd.Parameters.AddWithValue("#Type", type);
}
}
}
i want to call the return values from this method on page behind and bind it with label. please advice how to do it.
on my page behind on page load i have done like this
mail callmail = new mail()
now i label1.text how to assign return value to label1.text.
method returns 5 column and i have 5 label on my page so each column will assign to each label.
As per the discussion and assumptions I made following code
mail.cs
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace tempApp4
{
public class mail
{
public DataTable select(string type)
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("EmailSetup_CRUD", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "SELECT");
cmd.Parameters.AddWithValue("#Type", type);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
return dataSet.Tables[0];
}
}
}
}
}
WebForm1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="tempApp4.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="label1" runat="server" />
<asp:Label ID="label2" runat="server" />
<asp:Label ID="label3" runat="server" />
<asp:Label ID="label4" runat="server" />
<asp:Label ID="label5" runat="server" />
</form>
</body>
</html>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace tempApp4
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
mail mail = new mail();
var table = mail.select("TYPE_VALUE");
label1.Text = Convert.ToString(table.Rows[0][0]);
label2.Text = Convert.ToString(table.Rows[0][1]);
label3.Text = Convert.ToString(table.Rows[0][2]);
label4.Text = Convert.ToString(table.Rows[0][3]);
label5.Text = Convert.ToString(table.Rows[0][4]);
}
}
}
SqlDataAdapter "adapter" used to fetch records from the DB and fill it in dataSet. Data set holds many table as your procedure returns single table the "select" method returns single table at the end as:
return dataSet.Tables[0];
Thus "select" method have return type as "DataTable". Then finally access returned value in code behind using mail class's object and filling the labels by accessing the column as follows:
label1.Text = Convert.ToString(table.Rows[0][0]);
The first 0 in "table.Rows[0][0]" is for rows and second is for column. For column optionally you can specify name of the column as:
label1.Text = Convert.ToString(table.Rows[0]["COLUMN_NAME"]);
Since I don't know the column names I am using indexing.
Hope it helps
I have some problems with adding Html Editor to asp.net web forms.In admin panel,I want to add Html Editor to my text area in order to make a cool User Interface.I have .aspx such as:
<%# Page Title="" Language="C#" MasterPageFile="~/admin/IncubatorAdmin.master"
AutoEventWireup="true" CodeFile="AddFAQ.aspx.cs" Inherits="admin_AddFAQ" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<section id="main" class="column">
<article class="module width_full">
<header><h3>Post FAQ </h3></header>
<div class="module_content">
<fieldset style="width: 60%; float: left; margin-right: 3%;">
<label>Content</label>
<asp:TextBox ID="txtContent" TextMode="MultiLine" Columns="50" Rows="20" runat="server"/>
</fieldset>
<asp:Label ID="ResultLabel" runat="server" Text=""></asp:Label>
<div class="clear"></div>
</div>
<footer>
<div class="submit_link">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Publish FAQ" class="alt_btn" />
</div>
</footer>
</article><!-- end of post new article -->
</section>
and C# code :
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
public partial class admin_AddFAQ : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
String cs = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection cn = new MySqlConnection(cs))
{
MySqlCommand command = new MySqlCommand(StoredProcedures.select_faq, cn);
command.CommandType = CommandType.StoredProcedure;
int fid = 1;
command.Parameters.AddWithValue("fid", fid);
command.Parameters["fid"].Direction = ParameterDirection.Input;
cn.Open();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtContent.Text = (String)reader[1];
}
reader.Close();
cn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
String cs = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection cn = new MySqlConnection(cs))
{
MySqlCommand command = new MySqlCommand(StoredProcedures.update_faq, cn);
command.CommandType = CommandType.StoredProcedure;
int fid = 1;
command.Parameters.AddWithValue("fid", fid);
command.Parameters["fid"].Direction = ParameterDirection.Input;
command.Parameters.AddWithValue("fcontent", txtContent.Text);
command.Parameters["fcontent"].Direction = ParameterDirection.Input;
cn.Open();
if (command.ExecuteNonQuery() > 0)
{
ResultLabel.Text = "";
ResultLabel.Text = "FAQ page successfully updated";
}
cn.Close();
}
}
}
What changes should I do on .aspx, c# and web.config?Please help me...
You can use ajax control toolkit HTMLEditorExtender
Try http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/HtmlEditorExtender/HTMLEditorExtender.aspx
On page load I am extracting the parameter from the query string and inserting into the database.
here is the web.config file
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="MyConsString" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=MCAS_TEST;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
</configuration>
Here is my aspx page coding
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Sample Configuration Page</title>
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td>IP_Address:</td>
<td>
<asp:TextBox ID="x" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>MAC_Address:</td>
<td>
<asp:TextBox ID="y" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</div>
<asp:Button ID="Button1" runat="server" Text="Save"/>
</form>
</body>
</html>
The C# Code behind the aspx page is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["x"] != null)
{
insertData();
}
}
public void insertData()
{
using (SqlConnection con = new SqlConnection("MyConsString"))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Test(x, y) VALUES(#x, #y)", con))
{
cmd.Parameters.Add(new SqlParameter("x", Request.QueryString["x"]));
cmd.Parameters.Add(new SqlParameter("y", Request.QueryString["y"]));
cmd.ExecuteNonQuery();
}
}
catch (Exception Ex)
{
// Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
Response.Write("Unable To Save Data. Error - " + Ex.Message);
}
}
}
}
Now while executing it I am having error that Format of the initialization string does not conform to specification starting at index 0.
I am not getting why...
I modified my own code after some research which is as follows and it worked..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["x"] != null)
{
if (Request.QueryString["y"] != null)
{
insertData();
}
}
// else
// {
// Response.Redirect("http://localhost:53627/Default.aspx");
// }
}
public void insertData()
{
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Test(x, y) VALUES(#x, #y)", con))
{
cmd.Parameters.Add(new SqlParameter("x", Request.QueryString["x"]));
cmd.Parameters.Add(new SqlParameter("y", Request.QueryString["y"]));
cmd.ExecuteNonQuery();
}
}
catch (Exception Ex)
{
// Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
Response.Write("Unable To Save Data. Error - " + Ex.Message);
}
}
}
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
}
}
I am new to ASP.NET
Someone in this forum helped me how to get the dropdown list work wth user countrol and it is working.
In my user control file, VendorListControl.ascx, I have this code below. Please assume that the VendorListControl.ascx.cs works correctly, which is when I select a VendorName, it will fired "ddlVendor_SelectedIndexChanged" to refreshed the "ddlVendorBUList" dropdown list.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="VendorListControl.ascx.cs" Inherits="MyNamespace.VendorListControl" %>
<asp:DropDownList runat="server" ID="ddlVendorList" onselectedindexchanged="ddlVendor_SelectedIndexChanged" AutoPostBack="True" />
<asp:DropDownList runat="server" ID="ddlVendorBUList" AutoPostBack="True" />
<asp:Label runat="server" ID="lblMessage" />
My VendorListControl.ascx.cs code:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MyNamespace
{
public partial class VendorListControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillVendors();
}
}
protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
{
int VendorID = Convert.ToInt32(ddlVendorList.SelectedValue.ToString());
FillVendorBU(VendorID);
}
private void FillVendors()
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorID, VendorName FROM MDF_Vendor";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd; ;
conn.Open();
dAdapter.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
this.ddlVendorList.DataSource = objDs.Tables[0];
this.ddlVendorList.DataTextField = "VendorName";
this.ddlVendorList.DataValueField = "VendorID";
this.ddlVendorList.DataBind();
this.ddlVendorList.Items.Insert(0, "-- Select --");
}
else
{
this.lblMessage.Text = "No Vendor Found";
}
}
private void FillVendorBU(int VendorID)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorBUID, VendorBUName FROM dbo.MDF_VendorBU WHERE VendorID = #VendorID";
cmd.Parameters.AddWithValue("#VendorID", VendorID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlVendorBUList.DataSource = objDs.Tables[0];
ddlVendorBUList.DataTextField = "VendorBUName";
ddlVendorBUList.DataValueField = "VendorBUID";
ddlVendorBUList.DataBind();
ddlVendorBUList.Items.Insert(0, "--Select--");
}
else
{
lblMessage.Text = "No states found";
}
}
}
}
Next, in my CreateNewRecord.aspx page, I have this code to include both dropdown list from user control. And I can see the dropdown lists works properly.
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl runat="server" />
</td>
</tr>
The problem is related to the ID of those two dropdown lists. When I attemp to do the insert record, it seems not to detect the ID for "ddlVendorList" and "ddlVendorBUList" come from user control ascx page. Error " The name 'ddlVendorList' does not exist in the current context"
ExecuteInsert(ddlVendorList.SelectedItem.Text,
ddlVendorBUList.SelectedItem.Text,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
Response.Write("<b>Record was successfully added!</b>");
I know I am new to ASP.NET, so please help.
You can put two properties in your VendorListControl to get the ddlVendorList selectedItem text and the ddlVendorBUList selectedItem text.
In VendorListControl.ascx.cs :
public string GetDdlVendorListSelectedItemText
{
get { return this.ddlVendorList.text; }
}
public string GetDdlVendorBUListSelectedItemText
{
get { return this.ddlVendorBUList.text; }
}
Then from your page CreateNewRecord, you can access those properties. You just need to add an id to your control :
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl id="vendorListControl" runat="server" />
</td>
</tr>
And you can access your properties like this in CreateNewRecord.aspx.cs :
ExecuteInsert(this.vendorListControl.GetDdlVendorListSelectedItemText,
this.vendorListControl.GetDdlVendorBUListSelectedItemText,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
You define public property who return SelectedItem.Text in your UserControl.
User Control (Ascx)
public string YourValue
{
get
{
return ddlVendorList.SelectedItem.Text;
}
}
Page (Aspx)
You can use your public property : YourValue.
ExecuteInsert(YourValue,
....... );
Nota : if you wish set value, you define setter on your property
After your update add theses properties
public string YourDdlVendorListSelectedItemText
{
get
{
return this.ddlVendorList.text;
}
}
public string YourDdlVendorBUListSelectedItemText
{
get
{
return this.ddlVendorBUList.text;
}
}