ASP.NET C# - Dropdown list by using User Control - asp.net

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;
}
}

Related

Ajaxtoolkit - Autocomplete dont do anything when i click

I have tried everything and nothing works, i have no clue now. I used an example, that used to work ones but dont anymore. I used this example
https://www.aspsnippets.com/Articles/AJAX-AutoCompleteExtender-Example-in-ASPNet.aspx
And download the ajaxtoolkit from here
https://www.devexpress.com/products/ajax-control-toolkit/
I have scriptmanager in the top of the page and it looks like this.
This is my code
Masterpage.master
<asp:TextBox ID="txtContactsSearch" aria-describedby="basic-addon2" class="form-control-header" placeholder="Søg her ..." runat="server"></asp:TextBox> <cc1:AutoCompleteExtender ServiceMethod="SearchCustomers" MinimumPrefixLength="2" ServicePath="MasterPage.master" CompletionInterval="100" EnableCaching="false" CompletionSetCount="10" TargetControlID="txtContactsSearch" ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false"></cc1:AutoCompleteExtender>
My codebehind
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchCustomers(string prefixText, int count)
{
using (MySqlConnection conn = new MySqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString;
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "select Produktnavn from Produkter where " +
"Produktnavn like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(sdr["Produktnavn"].ToString());
}
}
conn.Close();
return customers;
}
}
}

ajaxToolkit:CascadingDropDown got error

I want to create cascadingdropdown using ajaxtoolkit but having error.
since newer version of ajaxcontroltoolkit have remove ToolkitScriptManager, so i use scriptmanager
<ajaxToolkit:CascadingDropDown
ID="cdlOffice"
TargetControlID="DropDownList1"
PromptText="Select Office"
PromptValue=""
ServicePath="~/WebService1.asmx"
ServiceMethod="GetLocation"
runat="server"
Category="LocationId"
LoadingText="Loading..." />
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="DropDownList1" CssClass="col-md-2 control-label">Location</asp:Label>
<div class="col-md-10">
<asp:DropDownList id="DropDownList1" runat="server" class="select2-me" data-placeholder="--SELECT--" data-rule-required="true" style="width:250px;" />
</div>
</div>
and WebService1.asmx as follow
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public CascadingDropDownNameValue[] GetLocation(string knownCategoryValues)
{
string query = "SELECT DISTINCT ITOFF_NAME, ITOFF_ID FROM ITOFF_TBL ORDER BY ITOFF_NAME";
List<CascadingDropDownNameValue> Location = GetData(query);
return Location.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] GetFloor(string knownCategoryValues)
{
string Location = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)["LocationId"];
string query = string.Format("SELECT ITOFF_LEVEL, ITOFF_ID FROM ITOFF_TBL WHERE ITOFF_NAME = {0}", Location);
List<CascadingDropDownNameValue> Floor = GetData(query);
return Floor.ToArray();
}
private List<CascadingDropDownNameValue> GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["ITFORMConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
cmd.Connection = con;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
values.Add(new CascadingDropDownNameValue
{
name = reader[0].ToString(),
value = reader[1].ToString()
});
}
reader.Close();
con.Close();
return values;
}
}
}
}
i'm having error showing
Unhandled exception at line 6, column 97862 in
http://localhost:60461/Scripts/WebForms/MsAjax/MicrosoftAjax.js
0x800a138f - JavaScript runtime error: Unable to get property
'webServiceFailedNoMsg' of undefined or null reference
all the code i learn from googling. is there anything missing or did wrong?
Try removing the String Param 'knownCategoryValues' from you getLocation() web method definition:
[WebMethod]
public CascadingDropDownNameValue[] GetLocation()
{
string query = "SELECT DISTINCT ITOFF_NAME, ITOFF_ID FROM ITOFF_TBL ORDER BY ITOFF_NAME";
List<CascadingDropDownNameValue> Location = GetData(query);
return Location.ToArray();
}
And remove locationID property from the from the Cascading DropDown definition.
Or, if you are getting the locationID from another dropdown then leave it in and define it as the ParentControlID

ASP.NET Listview.selectedindex property goes crazy

I'm deleting a single database record from a listview and after deleting I try to navigate in my listview using listView1.selectedindex property, but I have noticed that it highlights the incorrect record (for example I set listView1.selectedindex to 1 but it displays a record which has index 0) . What is wrong? Please help!
protected void deleteButton_Click(object sender, EventArgs e)
{
int id = int.Parse(((Label)ListView1.Items[ListView1.SelectedIndex].FindControl("idLabel")).Text);
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
BindDataFromBaseToListView method looks so:
private void BindDataFromBaseToListView()
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("select * from Employee", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
ListView1.DataSourceID = null;
ListView1.DataSource = dTable;
ListView1.DataBind();
}
conn.Close();
}
Instead of using deleteButton_Click event you could use your ListView's OnItemCommand event to get the selected row values and delete the item that you want like the code below:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
int id = 0;
if(int.TryParse((e.Item.FindControl("idLabel") as Label).Text, out id))
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
}
}
And on your control's element will look like this:
<asp:ListView ID="ListView1" runat="server" OnItemCommand="ListView1_ItemCommand" .. >
...
<ItemTemplate>
<asp:Button runat="server" CommandName="delete" Text="Delete" ID="DeleteButton" />
...
Let me know if you still have issue with it.

Show Images from Database ASP.Net

I am new to ASP.net and have some problem to show images. My designer code is as bellow.
<div id="directory-logo-wrapper" class="floatright">
<table id="wrapper1" runat="server">
<tr>
<td>
<img src="../images/companylogo.png" alt="LogoWrapper" />
<%--<asp:Image ID="Image1" runat="server" Visible="true" alt="LogoWrapper" />--%>
</td>
</tr>
</table>
</div>
My code behind code is as bellow.
protected void ShowImageFile(object sender, EventArgs e)
{
byte[] bytes = {};
bytes = (byte[])GetData("SELECT UploadedLogo FROM Projects WHERE ProjectId =" + id).Rows[0]["UploadedLogo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
//Image1.ImageUrl = "data:image/png;image/jpg;base64," + base64String;
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConnectionInfo.GetConnectionString();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
Problem: how to set table:wrapper1 img src in code behind because it does not shown in code behind. I tried to do with Image1 but its also not accessing in code behind.
Please help me.
Thanks, Raja
Try Like this
<div id="directory-logo-wrapper" class="floatright">
<table id="wrapper1" runat="server">
<tr>
<td>
<img id="myimage" runat="server" src="../images/companylogo.png" />
</td>
</tr>
</table>
</div>
You can access Src from Code Behind
Try like this
'Get byte array from image file in the database with basic query
SqlDataAdapter myAdapter1 = new SqlDataAdapter("Select [logo] FROM [dbo].[tblCompanyInfo]", GlobalUser.currentConnectionString);
DataTable dt = new DataTable();
myAdapter1.Fill(dt);
foreach (DataRow row in dt.Rows)
{
// Get the byte array from image file
byte[] imgBytes = (byte[])row["logo"];
// If you want convert to a bitmap file
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap MyBitmap = (Bitmap)tc.ConvertFrom(imgBytes );
string imgString = Convert.ToBase64String(imgBytes);
// Set the source with data:image/bmp
myimage.Src = String.Format("data:image/Bmp;base64,{0}\"", imgString);
}
EDIT
Access Image inside GridView
private string m_ConcatUrl;
protected void gridView_RowDataBound(Object sender, GridViewRowEventArgs args)
{
if(args.Row.RowType == DataControlRowType.DataRow)
{
Image imgCtrl = (Image) args.Row.FindControl("imgCtrl");
imgCtrl.ImageUrl = m_ConcatUrl;
}
}
(or)
private string m_ConcatUrl;
protected void gridView_RowDataBound(Object sender, GridViewRowEventArgs args)
{
if(args.Row.RowType == DataControlRowType.DataRow)
{
HtmlImage img = (HtmlImage) args.Row.FindControl("imgCtrl");
imgCtrl.Src= m_ConcatUrl;
}
}
You can try following way:
HTML:
<div id="directory-logo-wrapper" class="floatright">
<table id="wrapper1" runat="server">
<tr>
<td>
<img src='<%# ImageUrl(ProjectId) %>' alt="LogoWrapper" />
<%--<asp:Image ID="Image1" runat="server" Visible="true" alt="LogoWrapper" />--%>
</td>
</tr>
</table>
</div>
Code Behind:
private string ImageUrl(int ProjectId)
{
byte[] bytes = {};
bytes = (byte[])GetData("SELECT UploadedLogo FROM Projects WHERE ProjectId =" + ProjectId).Rows[0]["UploadedLogo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
return "data:image/png;image/jpg;base64," + base64String;
//Image1.ImageUrl = "data:image/png;image/jpg;base64," + base64String;
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConnectionInfo.GetConnectionString();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
Hope this helps.

ASP.net Repeater not binding values

I have a repeater defined as
<asp:Repeater id="rep1" runat="server">
<ItemTemplate>
<%#Eval("name")%>
</ItemTemplate>
</asp:Repeater>
The code behind is as
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #"Data Source=XXXXXX;Trusted_Connection=yes;database=master";
xconn.Open();
lbl1.Text = "Connected to SQL";
SqlCommand ycmd = new SqlCommand("select * from student",xconn);
SqlDataReader dr = ycmd.ExecuteReader();
cdcatalog.DataSource = dr;
cdcatalog.DataBind();
}
catch (Exception)
{
lbl1.Text= "Cannot connect to SQL";
}
Why does it not bind the data in the repeater?
Why are you binding data readers to a repeater? I would recommend you using strongly typed objects. So start by defining a model that will represent your data:
public class Student
{
public string Name { get; set; }
}
then a method to fetch those students:
public IEnumerable<Student> GetStudents()
{
using (var conn = new SqlConnection("Data Source=XXXXXX;Trusted_Connection=yes;database=master"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Students;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new Student
{
Name = reader.GetString(reader.GetOrdinal("Name"));
}
}
}
}
}
and then bind the repeater:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rep1.DataSource = GetStudents().ToArray();
rep1.DataBind();
}
}
and in the view:
<asp:Repeater id="rep1" runat="server">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:Repeater>
Also note that the name of the repeater is rep1 so that's what you should use in your code behind.
the ID of your repeater is rep1 whereas you are databinding cdcatalog. I guess your problem is there. What is this cdcatalog?

Resources