I have 3 dropdownlist: select year, select make, select model. Upon select model the results should appear in a gridview. My tables are:
Makes with [(pk)MakeID, MakeName]; Models with [(pk)ModelID, Make_ID, ModelYear, ModelName]; and Wipers with [(pk)WiperID, Model_ID, Description, Emplacement, Price]. When I step through debug, I see 6 counts of records found, but I do not see it in gridview
I've looked at these for help, but no answers
ASP.net DropDownList populates GridView
Binding gridview with arraylist asp.net/c#
My Default.aspx
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="wrapper" align="center">
<asp:DropDownList ID="ddlYear" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Year_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlMake" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Make_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlModel" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="Get_Wipers_By_Model">
</asp:DropDownList>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:GridView ID="grdWiperList" runat="server">
</asp:GridView>
</form>
My Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Year drop down list is populated on page load
string query = "SELECT DISTINCT ModelYear FROM Models";
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddlYear.DataSource = cmd.ExecuteReader();
ddlYear.DataValueField = "ModelYear";
ddlYear.DataBind();
conn.Close();
}
}
ddlYear.Items.Insert(0, new ListItem("Select Year", "0"));
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
conn.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void Year_Changed(object sender, EventArgs e)
{
//the Makes drop down list is populated on OnSelectedIndexChange event of the Year_Changed event
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Clear();
ddlModel.Items.Clear();
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearId = int.Parse(ddlYear.SelectedItem.Value);
if (yearId > 0)
{
string query = string.Format("SELECT DISTINCT MakeID, MakeName FROM Makes JOIN Models ON Make_ID = MakeID WHERE ModelYear = {0}", yearId);
BindDropDownList(ddlMake, query, "MakeName", "MakeID", "Select Make");
ddlMake.Enabled = true;
}
}
protected void Make_Changed(object sender, EventArgs e)
{
ddlModel.Enabled = false;
ddlModel.Items.Clear();
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearID = int.Parse(ddlYear.SelectedItem.Value);
int makeId = int.Parse(ddlMake.SelectedItem.Value);
if (makeId > 0)
{
string query = string.Format("SELECT ModelID, ModelName FROM Models WHERE ModelYear = {0} AND Make_ID = {1}", yearID, makeId);
BindDropDownList(ddlModel, query, "ModelName", "ModelID", "Select Model");
ddlModel.Enabled = true;
}
}
protected void Get_Wipers_By_Model(object sender, EventArgs e)
{
grdWiperList.DataSource = Connection.GetWipersByModel
(!IsPostBack ? "%" : ddlModel.SelectedValue);
grdWiperList.DataBind();
}
}
My Connection.cs
public static ArrayList GetWipersByModel(string modelType)
{
ArrayList listResults = new ArrayList();
string query = string.Format
("SELECT * FROM Wipers WHERE Model_ID LIKE '{0}'", modelType);
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = query;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int wiperID = reader.GetInt32(0);
int model_id = reader.GetInt32(1);
string description = reader.GetString(2);
string itemNo = reader.GetString(3);
string emplacement = reader.GetString(4);
decimal price = reader.GetDecimal(5);
Wipers wipers = new Wipers(wiperID, model_id, description, itemNo, emplacement, price);
listResults.Add(wipers);
}
}
finally
{
conn.Close();
}
return listResults;
}
I think this because the updatePanel control try to add trigger between UpdatePanel control and DropDownList Control
Related
When I run application dropdown menu's value are always set to 0 and displaying result in Report.
I want to modify these to add text in DropDownMenu and when user is not selected anything it should return all data, if user select value from dropdown it should return value which user selected.
First DropDownMenu
public void FillOrgUnit()
{
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
{
string com = "SELECT DISTINCT OrgUnitID FROM tblZaposleni_AD ORDER BY OrgUnitID ASC";
SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
DataTable dt = new DataTable();
adpt.Fill(dt);
ddlOrgUnit.DataSource = dt;
ddlOrgUnit.DataTextField = "OrgUnitID";
ddlOrgUnit.DataValueField = "OrgUnitID";
ddlOrgUnit.DataBind();
ddlOrgUnit.Items.Insert(0, new ListItem("-- Izaberi Org Jedinicu --", "NULL"));
}
}
Second dropdown menu:
public void FillStatus()
{
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
{
string com = "SELECT DISTINCT Status FROM tblZaposleni_AD";
SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
DataTable dt = new DataTable();
adpt.Fill(dt);
ddlStatus.DataSource = dt;
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = "Status";
ddlStatus.DataBind();
ddlStatus.Items.Insert(0, new ListItem("-- Izaberi Status --", "NULL"));
}
}
enter image description here
HTML
<div>
<p class="auto-style1">
Izaberi Izvjestaj :
<br class="auto-style1" />
<asp:DropDownList ID="ddlReportName" runat="server" Width="168px" DataTextField="Value" DataValueField="Key" OnSelectedIndexChanged="ddlReportName_SelectedIndexChanged" Height="16px">
</asp:DropDownList>
<br class="auto-style1" />
Org Unit
<br class="auto-style1" />
<asp:DropDownList ID="ddlOrgUnit" runat="server" Height="17px" OnSelectedIndexChanged="ddlOrgUnit_SelectedIndexChanged" Width="157px" AppendDataBoundItems="True">
<asp:ListItem Value="">-- Izaberi Org Jedinicu --</asp:ListItem>
</asp:DropDownList>
<br class="auto-style1" />
Status:
<br class="auto-style1" />
<asp:DropDownList ID="ddlStatus" runat="server" Height="16px" OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged1" Width="147px" AppendDataBoundItems="True">
<asp:ListItem Value="">-- Izaberi Status --</asp:ListItem>
</asp:DropDownList>
</p>
<p class="auto-style1">
<br class="auto-style1" />
<%--Show--%>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Filter" Width="224px" />
</p>
</div>
Page_Load where I call FillStatus and FillOrgUnt metod
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string path = #"\Reports\";
CustomReportStorageWebExtension reportsStorage = new CustomReportStorageWebExtension(path);
ddlReportName.DataSource = reportsStorage.GetUrls();
ddlReportName.DataBind();
//Call function for populate cb
FillStatus();
FillOrgUnit();
}
else
{
XtraReport reportToOpen = null;
switch (ddlReportName.SelectedValue)
{
case "Zaposleni 1":
reportToOpen = new ZaposleniSaoOsig1();
break;
case "Zaposleni 2":
reportToOpen = new ZaposleniSaoOsig2();
break;
case "Zaposleni 3":
reportToOpen = new ZaposleniSaoOsig3();
break;
}
GetReports(reportToOpen);
ASPxWebDocumentViewer1.OpenReport(reportToOpen);
}
}
Main function which filters Status and OrgUnit
private void GetReports(XtraReport report)
{
try
{
string connString = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
string strproc = "TestReport";
using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.SelectCommand.Parameters.Add("#Status", SqlDbType.Bit).Value = ddlStatus.SelectedValue == "1" ? true : false;
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = ddlOrgUnit.SelectedValue;
sda.Fill(ds);
string[] arrvalues = new string[ds.Tables[0].Rows.Count];
for (int loopcounter = 0; loopcounter < ds.Tables[0].Rows.Count; loopcounter++)
{
//assign dataset values to array
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["PrezimeIme"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["NetworkLogin"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["Status"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["OrgUnitID"].ToString();
}
report.DataSource = ds;
report.DataMember = ds.Tables[0].TableName.ToString();
}
}
catch (Exception)
{
throw;
}
}
As well as stored procedure which return filtered Report by Status Or OrgId
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[TestReport]
(
#Status bit,
#OrgJed int
)
AS
BEGIN
SELECT PrezimeIme, NetworkLogin, Status, OrgUnitId, DT_Creat, DT_Modif
FROM [DesignSaoOsig1].[dbo].[tblZaposleni_AD]
WHERE (#Status IS NULL OR Status = #Status)
AND (#OrgJed IS NULL OR OrgUnitID = #OrgJed)
END
You can do the following to bind the datasource:
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
{
string com = "SELECT DISTINCT OrgUnitID FROM tblZaposleni_AD ORDER BY OrgUnitID ASC";
SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
DataTable dt = new DataTable();
adpt.Fill(dt);
ddlOrgUnit.DataSource = dt;
ddlOrgUnit.DataBind();
ddlOrgUnit.DataTextField = "text field you want to bind";
ddlOrgUnit.DataValueField = "value field you want to bind";
ddlOrgUnit.DataBind();
//add default value - you can then remove the default value from html
ddlOrgUnit.Items.Insert(0, new ListItem("-- Izaberi Org Jedinicu --","N/A")
}
The above logic should be done in the FillStatus() method too.
In your Page_Load method do the following
if (!IsPostBack)
{
FillStatus();
FillOrgUnit();
}
In the ddlOrgUnit_SelectedIndexChanged - for example - you will handle the value selected by the user accordingly - and filter for the select value - or return all.
NOTE
When you fill your DataTable(dt) from your query - you will have a table structure from the following SQL table tblZaposleni_AD
In here ddlOrgUnit.DataTextField = "text field you want to bind"; you will add the column name you want to bind as text file - eg Name
NOTE
How to use tryparse in C#
if (Int32.TryParse(ddlStatus.SelectedValue, out int theValue))
{
//is not null
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = theValue
}
// is null and you dont pass the parameter
Then in your stored procedure you set the default value for #OrgJed int to be null
ALTER PROCEDURE [dbo].[TestReport]
(
#Status bit,
#OrgJed int = NULL
)
using(sqlconnection con=new sqlconnection(cs))
{
sqlcommand cmd=new sqlcommand("select [datatextfield], [datavaluefield] from tbl",con);
sqldatareader rdr=cmd.executereader();
dropdown.datasource=rdr;
dropdown.datatextfield=rdr[0];
dropdown.datavaluefield=rdr[1];
dropdown.databind();
}
I've created a dropdownlist, and tried clicking on the first selection but there was no firing of the SelectedIndexChanged event. However, it worked perfectly fine for the rest of the options in the dropdownlist.
Here are my codes:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string member = (String)Session["ssmem"];
if (!IsPostBack)
{
if (Session["ssmem"] == null)
Response.Redirect("LoginforAccess.aspx");
else
{
Response.ClearHeaders();
Response.AddHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
Response.AddHeader("Pragma", "no-cache");
//if go back then must log in --2
}
//Dropdownlist
string strConnectionString =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
//STEP1 : Define a connection to Database
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strcommand = "Select Username from [User] WHERE (UsergroupID = (SELECT UsergroupID FROM [User] AS User_1 WHERE (Username = #user)))";
SqlCommand cmd = new SqlCommand(strcommand, myConnect);
// cmd.Parameters.AddWithValue("#usergrp", groupid);
cmd.Parameters.AddWithValue("#user", member);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader();
DropDownList1.DataSource = reader;
DropDownList1.DataTextField = "Username";
DropDownList1.DataValueField = "Username";
DropDownList1.DataBind();
reader.Close();
myConnect.Close();
}
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (Session["ssmem"] != null)
MasterPageFile = "User.master";
//change the master page --1
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//chosen name to display stats
string choseuser = "";
choseuser = DropDownList1.SelectedItem.Text;
Response.Redirect("Substats.aspx?choseuser=" + choseuser);
}
}
Source view for dropdownlist:
<asp:DropDownList ID="DropDownList1" runat="server" Width="200px" Height="35px"
AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged"
ViewStateMode="Enabled">
</asp:DropDownList>
We have to add first item as title to the dropdownlist,
and instead of using datasource used dr.Read() in while loop for adding the items on dropdownlist.
This problem occurs because in dropdownlist first item is selected bydefault and it is not reflected on selection
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" ViewStateMode="Enabled">
<asp:ListItem>Select College</asp:ListItem>
<!--Add one item as title into dropdownlist in edit item of dropdownlist-->
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("hello");
try
{
string sel = "select name from websites";
SqlCommand cmd = new SqlCommand(sel,con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
/* DropDownList1.DataSource = dr;
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();*/
while (dr.Read())//used dr.read() instead of datasource
{
DropDownList1.Items.Add(dr["name"].ToString());
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("select url from websites where name = #itm", con);
cmd.Parameters.AddWithValue("#itm", DropDownList1.SelectedItem.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
Response.Redirect(dr["url"].ToString());
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
I want to get what I write in the textbox but always get the "" string. I can't find the value when I type something else into the textboxT_T.
Here is the Gridview code:
<div style="margin:0 auto;width:900px;">
<asp:Label ID="USER_header" runat="server"
Text="一.先新增用戶" CssClass="=text-center"></asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter = "true" Width="900" OnDataBound = "OnDataBound" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="工號" SortExpression="BS_ID">
<ItemTemplate>
<asp:Label ID="lblBSID" runat="server"
Text='<%# Eval("BS_ID") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_ID_tb" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="中文姓名" SortExpression="BS_NAME_CHT">
<ItemTemplate>
<asp:Label ID="lblBS_NAME_CHT" runat="server"
Text='<%# Eval("BS_NAME_CHT") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_NAME_CHT_tb" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="英文姓名" SortExpression="BS_NAME_ENG">
<ItemTemplate>
<asp:Label ID="lblBS_NAME_ENG" runat="server"
Text='<%# Eval("BS_NAME_ENG") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_NAME_ENG_tb" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="部門" SortExpression="BS_DEPT">
<ItemTemplate>
<asp:Label ID="lblBS_DEPT" runat="server"
Text='<%# Eval("BS_DEPT") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList1" Width="200" runat="server">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:LinkButton ID="btnInsert" runat="server"
onclick="lbInsert_Click" Text="新增" CommandName="Insert"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>`
Here is the complete code:
private DataSet _dataSet;
private DataSet _dataSetHKTEL;
private DataSet _datasetHKMOBILE;
private string _value;
protected void Page_Load(object sender, EventArgs e)
{
ShowData();
GridView1.FooterRow.Visible = false;
lblinsertuser.Visible = false;
lbCancelSave.Visible = false;
//if (Session["key_pass"] == null)
//{
// Response.Write("<script>alert('YOUR ACCESS DENY! 你沒有權限進入此頁面');location.href='Default.aspx';</script>");
//}
}
private void Viewtable()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 BS_ID,BS_NAME_CHT,BS_NAME_ENG,BS_DEPT FROM BS_USER ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateDataTable();
conn.Open();
da1.Fill(finaldata);
this._dataSet = new DataSet();
this._dataSet.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private void ViewItnlHKTel()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 DA_TEL_NO,DA_USER FROM DA_ITNL_HK_TEL ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateTable();
conn.Open();
da1.Fill(finaldata);
this._dataSetHKTEL = new DataSet();
this._dataSetHKTEL.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private void ViewITNLHKMOBILE()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 DA_PHONE_NO,DA_USER FROM DA_HK_MOBILE ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateMOBILE_HK();
conn.Open();
da1.Fill(finaldata);
this._datasetHKMOBILE = new DataSet();
this._datasetHKMOBILE.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private DataTable GenerateDataTable()
{
DataTable table = new DataTable();
table.Columns.Add("BS_ID", typeof(string));
table.Columns.Add("BS_NAME_CHT", typeof(string));
table.Columns.Add("BS_NAME_ENG", typeof(string));
table.Columns.Add("BS_DEPT", typeof(string));
return table;
}
private DataTable GenerateTable()
{
DataTable table = new DataTable();
table.Columns.Add("DA_USER", typeof(string));
table.Columns.Add("DA_ITNL_HK_TEL", typeof(string));
return table;
}
private DataTable GenerateMOBILE_HK()
{
DataTable table = new DataTable();
table.Columns.Add("DA_USER", typeof(string));
table.Columns.Add("DA_PHONE_NO", typeof(string));
return table;
}
private void ShowData()
{
Viewtable();
GridView1.DataSource = this._dataSet;
GridView1.DataBind();
ViewItnlHKTel();
ADD_HK_TEL.DataSource = this._dataSetHKTEL;
ADD_HK_TEL.DataBind();
ViewITNLHKMOBILE();
ADD_HK_MOBILE.DataSource = this._datasetHKMOBILE;
ADD_HK_MOBILE.DataBind();
}
protected void lbladd_Click(object sender, EventArgs e)
{
//TextBox id = GridView1.FooterRow.FindControl("BS_ID_tb") as TextBox;
////string strBS_ID = (GridView1.FooterRow.FindControl("BS_ID_tb") as TextBox).Text;
//DropDownList DEPT_ddl = GridView1.FooterRow.FindControl("DropDownList1") as DropDownList;
////string strBS_ID = BS_ID_tb.Text;
////string strBS_NAME_CHT = BS_NAME_CHT_tb.Text;
////string strBS_NAME_ENG = BS_NAME_ENG.Text;
//string strBS_DEPT = DEPT_ddl.SelectedItem.Value;
////using (SqlConnection conn = new SqlConnection(this._connectionString))
////{
//// string query = "INSERT INTO BS_USER(BS_ID , BS_NAME_CHT , BS_NAME_ENG , BS_DEPT) VALUES (#BS_ID , #BS_NAME_CHT , #BS_NAME_ENG , #BS_DEPT)";
//// SqlCommand cmd = new SqlCommand(query, conn);
//// cmd.Parameters.Clear();
//// cmd.Parameters.AddWithValue("#BS_ID", strBS_ID);
//// cmd.Parameters.AddWithValue("#BS_NAME_CHT", strBS_NAME_CHT);
//// cmd.Parameters.AddWithValue("#BS_NAME_ENG", strBS_NAME_ENG);
//// cmd.Parameters.AddWithValue("#BS_DEPT", strBS_DEPT);
//// conn.Open();
//// cmd.ExecuteReader();
//// conn.Close();
//// //Response.Redirect("");
////}
}
protected void lbInsert_Click(object sender, EventArgs e)
{
GridView1.FooterRow.Visible = true;
lblinsertuser.Visible = true;
lbCancelSave.Visible = true;
lbInsert.Visible = false;
}
protected void lbCancelSave_Click(object sender, EventArgs e)
{
GridView1.FooterRow.Visible = false;
lbInsert.Visible = true;
}
DataTable Selectindex()
{
DataTable dt = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT '請選擇部門' AS BS_NAME , '000' AS BS_ID UNION SELECT BS_NAME , BS_ID FROM BS_DEPT ORDER BY BS_ID ASC", conn))
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
}
}
catch (SqlException exc)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + exc.Message + "');", true);
}
catch (Exception exc)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + exc.Message + "');", true);
}
finally
{
}
return dt;
}
protected void OnDataBound(object sender, EventArgs e)
{
DropDownList DEPT_ddl = GridView1.FooterRow.FindControl("DropDownList1") as DropDownList;
DEPT_ddl.DataSource = Selectindex();
DEPT_ddl.DataTextField = "BS_NAME";
DEPT_ddl.DataValueField = "BS_ID";
DEPT_ddl.DataBind();
}
protected void lbSave_Click(object sender, EventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert",StringComparison.OrdinalIgnoreCase))
{
GridView GridView1= (GridView)sender;
TextBox BS_ID_tb = (TextBox)GridView1.FooterRow.FindControl("BS_ID_tb");
string str_BS_ID = BS_ID_tb.Text;
TextBox BS_NAME_CHT_tb = (TextBox)GridView1.FooterRow.FindControl("BS_NAME_CHT_tb");
string str_BS_NAME_CHT = BS_NAME_CHT_tb.Text;
TextBox BS_NAME_ENG_tb = (TextBox)GridView1.FooterRow.FindControl("BS_NAME_ENG_tb");
string str_BS_NAME_ENG_tb = BS_NAME_ENG_tb.Text;
DropDownList DEPT_ddl = (DropDownList)GridView1.FooterRow.FindControl("DropDownList1");
string str_DEPT_value = DEPT_ddl.SelectedItem.Value;
InsertData(str_BS_ID, str_BS_NAME_CHT, str_BS_NAME_ENG_tb, str_DEPT_value);
GridView1.ShowFooter = false;
ShowData();
GridView1.FooterRow.Visible = false;
lblinsertuser.Visible = false;
lbCancelSave.Visible = false;
}
}
private void InsertData(string BS_ID, string BS_NAME_CHT, string BS_NAME_ENG, string BS_DEPT)
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
conn.Open();
string sql = String.Format("Insert into BS_USER VALUES('{0}','{1}','{2}','{3}')", BS_ID, BS_NAME_CHT, BS_NAME_ENG, BS_DEPT);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}
}
View state's purpose is simple:
it's there to persist state across postbacks.
That's why you are getting the initial values like empty strings in the gridview. Setting the property EnableViewState="false" force to get the data by rebinding the control, not from the viewstate. To understand view state more, see here.
i am using sql query to fetch the data from one dropdown list and want to change the second dropdown list by filter data i mean i am selecting the 1st dropdown list and the 2nd drop downlist show all the customer but i want the specific customer by cardcode when i select cardcode.
kindly help, thanks in advance
here is my aspx.cs 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;
namespace StackOver
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadOptions();
}
}
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
string id, name, newName, name2;
SqlConnection connection = new SqlConnection("Data Source=adfsadf;Initial Catalog=TestDatabse;Persist Security Info=True;User ID=asd;Password=asdf");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT T1.CardCode , T1.CardName, T2.OpprId,T1.CntctPrsn, T2.CprCode,T2.MaxSumLoc FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode" , connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = id + " ---- " + name;
//name2 = id;
DropDownList1.Items.Add(new ListItem(newName, id));
name2 = CardCode.Rows[i]["CntctPrsn"].ToString();
DropDownList2.Items.Add(new ListItem(name2, name2));
}
}
//adapter.Fill(CardCode);
//DropDownList1.DataValueField = "CardCode";
//DropDownList1.DataTextField = "CardCode";
//DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("Data Source=mydtasrc;Initial Catalog=TestDatabs;Persist Security Info=True;User ID=asf;Password=asdfgh");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("SELECT CardCode, CardName, OpprId, CprCode,MaxSumLoc FROM OOPR WHERE CardCode = #CardCode", connection);
SqlCommand theCommand = new SqlCommand("SELECT T1.CardCode , T1.CardName, T2.OpprId, T1.CntctPrsn,T2.CprCode FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode where T1.CardCode=#CardCode", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selected);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
// Get the first row
// theReader.Read();
// Set the text box values
this.TextBox1.Text = theReader["CardCode"].ToString();
this.TextBox2.Text = theReader["CardName"].ToString();
this.TextBox5.Text = theReader["CprCode"].ToString();
this.TextBox3.Text = theReader["OpprId"].ToString();
this.DropDownList2.Text = theReader["CntctPrsn"].ToString();
// this.TextBox3 = reader.IsDBNull(TextBox3Index) ? null : reader.GetInt32(TextBox3Index)
// GenreID = reader.IsDBNull(genreIDIndex) ? null : reader.GetInt32(genreIDIndex)
// this.TextBox4.Text = theReader.GetString(3);
// TextBox5.Text = theReader.GetString(4);
// TextBox6.Text = theReader.GetString(5);
// TextBox7.Text = theReader.GetString(6);
}
connection.Close();
}
}
public object TextBox3Index { get; set; }
// protected void Button1_Click(object sender, EventArgs e)
// {
// SqlConnection connection = new SqlConnection();
// connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TestDataBaseConnectionString2"].ConnectionString;
// connection.Open();
// SqlCommand cmd = new SqlCommand();
// cmd.CommandText = "select * from OOPR";
// cmd.Connection = connection;
// SqlDataAdapter da = new SqlDataAdapter();
// da.SelectCommand = cmd;
// DataSet ds = new DataSet();
// da.Fill(ds, " OOPR");
// SqlCommandBuilder cb = new SqlCommandBuilder(da);
// DataRow drow = ds.Tables["OOPR"].NewRow();
// drow["CardCode"] = TextBox1.Text;
// drow["CardName"] = TextBox2.Text;
// drow["OpprId"] = TextBox3.Text;
// drow["CprCode"] = TextBox4.Text;
// drow["MaxSumLoc"] = TextBox5.Text;
// ds.Tables["OOPR"].Rows.Add(drow);
// da.Update(ds, " OOPR ");
// string script = #"<script language=""javascript"">
// alert('Information have been Saved Successfully.......!!!!!.');
// </script>;";
// Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
// }
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
using (connection)
{
// connection.Open();
SqlCommand insert = new SqlCommand("Insert into OOPR(CardCode, CardName, OpprId, CprCode,MaxSumLoc) values (#TextBox1,#TextBox2,#TextBox3,#TextBox4,#TextBox5 )", connection); //('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.Text + "','" + TextBox4.Text + "')", connection);
insert.Parameters.AddWithValue("#TextBox1", TextBox1.Text);
insert.Parameters.AddWithValue("#TextBox2", TextBox2.Text);
insert.Parameters.AddWithValue("#TextBox3", TextBox3.Text);
insert.Parameters.AddWithValue("#TextBox4", TextBox4.Text);
insert.Parameters.AddWithValue("#TextBox5", TextBox4.Text);
connection.Open();
// connection.CommandType=CommandType.Text;
// connection.commandType=CommandType.Text;
// try
// {
insert.ExecuteNonQuery();
connection.Close();
// }
//catch
//{
// TextBox5.Text = "Error when saving on database";
// connection.Close();
//}
//TextBox1.Text="";
//TextBox2.Text = "";
//TextBox3.Text = "";
//TextBox4.Text="";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Close", "window.close()", true);
// this.close();
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
and here is the apsx code
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="StackOver._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
</h2>
<br />
<p>
Business Partner Code :
<asp:TextBox ID="TextBox1" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Business Partner Name :
<asp:TextBox ID="TextBox2" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Opportunity No. :
<asp:TextBox ID="TextBox3" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Contact Person Name :
<asp:TextBox ID="TextBox4" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Total Amount Invoiced:
<asp:TextBox ID="TextBox5" runat="server" Width="193px" ></asp:TextBox>
</p>
<p>
Business partner Territory:
<asp:TextBox ID="TextBox6" runat="server" Width="174px" ></asp:TextBox>
</p>
<p>
Sales Employee:
<asp:TextBox ID="TextBox7" runat="server" Width="235px" ></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add"
Width="140px" />
<asp:Button ID="Button2" runat="server" Text="Cancel" Width="149px"
onclick="Button2_Click" />
</p>
</asp:Content>
Put your filtered customer into a DataTable(dt) and fill like this:
DropDownList2.DataTextField = "CustomerName";
DropDownList2.DataValueField = "CustomerID";
DropDownList2.DataSource = dt;
DropDownList2.DataBind();
The list2 will change its value once the list1 trigger the selectedindexchanged event.
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
string id, name, newName, name2;
SqlConnection connection = new SqlConnection("Data Source=adfsadf;Initial Catalog=TestDatabse;Persist Security Info=True;User ID=asd;Password=asdf");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT T1.CardCode , T1.CardName, T2.OpprId,T1.CntctPrsn, T2.CprCode,T2.MaxSumLoc FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode" , connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = id + " ---- " + name;
//name2 = id;
DropDownList1.Items.Add(new ListItem(newName, id));
//*******HERE*****//
DropDownList2.DataSource = CardCode;
DropDownList2.DataBind();
DropDownList2.DataValueField = "CardCode";
DropDownList2.DataTextField = "CntctPrsn";
//*******HERE*****//
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("Data Source=mydtasrc;Initial Catalog=TestDatabs;Persist Security Info=True;User ID=asf;Password=asdfgh");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("SELECT CardCode, CardName, OpprId, CprCode,MaxSumLoc FROM OOPR WHERE CardCode = #CardCode", connection);
SqlCommand theCommand = new SqlCommand("SELECT T1.CardCode , T1.CardName, T2.OpprId, T1.CntctPrsn,T2.CprCode FROM OCRD T1 left join OOPR T2 on T1.CardCode=T2.CardCode where T1.CardCode=#CardCode", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selected);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
this.TextBox1.Text = theReader["CardCode"].ToString();
this.TextBox2.Text = theReader["CardName"].ToString();
this.TextBox5.Text = theReader["CprCode"].ToString();
this.TextBox3.Text = theReader["OpprId"].ToString();
//*******AND HERE*****//
this.DropDownList2.SelectedValue = selected;
//*******AND HERE*****//
}
connection.Close();
}
}
I'm trying to create a Image Dynamically. I got the Link to the Image.
necessary code:
foreach (String pictureLink in imageLinks)
{
Image image = new Image();
image.ImageUrl = pictureLink;
imagesDiv.Controls.Add(image);
}
But nothing is happens.. How can I do that or what I'm doing wrong?
The Style, of how the pictures should be showed is Googleimagesearch result like..
EDIT:
There is one more thing I would do.. When adding the Placeholders (with the Image), they are showed after all Images where been loaded, but is it possible to add the placeholder with the image, right after it has been added?
take a look at this
Adding asp.net image to div
I think it should answer your questions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Types;
using BOO;
using BOFactory;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
namespace DAL
{
public class CustomerDAL:ICustomerDAL
{
List<ICustomerBO> emplist = new List<ICustomerBO>();
List<ICustomerBO> llist = new List<ICustomerBO>();
public List<ICustomerBO> DBbind()
{
string connectionstring = ";
SqlConnection connection = new SqlConnection(connectionstring);
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_databinding";
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string locn = reader["location"].ToString();
ICustomerBO loc = new CustomerBO(locn);
llist.Add(loc);
}
connection.Close();
return llist;
}
public int addemployee(ICustomerBO b)
{
string connectionstring = "Server= LENOVO\\SQLEXPRESS, Authentication=Windows Authentication, Database= tempdb";
SqlConnection connection = new SqlConnection(connectionstring);
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_addemployee";
command.Connection = connection;
command.Parameters.AddWithValue("#employeename", b.empname);
command.Parameters.AddWithValue("#dob", b.dob);
command.Parameters.AddWithValue("#location", b.location);
command.Parameters.AddWithValue("#gender", b.gender);
command.Parameters.AddWithValue("#doj", b.doj);
command.Parameters.AddWithValue("#experience", b.experience);
command.Parameters.AddWithValue("#CTC", b.ctc);
command.Parameters.AddWithValue("#designation", b.designation);
command.Parameters.AddWithValue("#unithead", b.unithead);
command.Parameters.AddWithValue("#projectid",b.projectid);
command.Parameters.AddWithValue("#id", 0);
command.Parameters["#id"].Direction = ParameterDirection.Output;
int rowaffected = command.ExecuteNonQuery();
connection.Close();
if(rowaffected>0)
{
return rowaffected;
}
else
{
return 0;
}
}
public bool LOGIN(ICustomerBO l)
{
bool flag = false;
string connectionstring = "Data Source=sql1;" + ";" + "user id=;"
+ "password=tcstvm;";
SqlConnection connection = new SqlConnection(connectionstring);
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_loginview";
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string name = reader["UserName"].ToString();
string pwd = reader["Password"].ToString();
if((name==l.name)&&(pwd==l.pwd))
{
flag = true;
}
}
connection.Close();
return flag;
}
public List<ICustomerBO> viewallListBO()
{
string ConnectionString = "";
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_viewemp7";
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int id = Convert.ToInt32(reader["id"]);
string name = reader["employeename"].ToString();
DateTime dob = Convert.ToDateTime(reader["dob"]);
string locn = reader["location"].ToString();
string gender = reader["gender"].ToString();
DateTime doj = Convert.ToDateTime(reader["doj"]);
int exp = Convert.ToInt32(reader["experience"]);
int ctc = Convert.ToInt32(reader["ctc"]);
string desg = reader["designation"].ToString();
string head = reader["unithead"].ToString();
int proj =Convert.ToInt32( reader["projectid"]);
ICustomerBO employee=BOFactory.CustomerBOFactory.ADDEMPLOYEE(id, name, dob, locn, gender, doj, exp, ctc, desg, head, proj);
emplist.Add(employee);
}
connection.Close();
return emplist;
}
public bool EDITCustomer(ICustomerBO bb)
{
bool flag = false;
string ConnectionString = "";
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_editemploye";
command.Connection = connection;
SqlConnection conn = new SqlConnection();
command.Parameters.AddWithValue("#id", bb.id);
command.Parameters.AddWithValue("#employeename", bb.empname);
command.Parameters.AddWithValue("#dob", bb.dob);
command.Parameters.AddWithValue("#location", bb.location);
command.Parameters.AddWithValue("#gender", bb.gender);
command.Parameters.AddWithValue("#doj", bb.doj);
command.Parameters.AddWithValue("#experience", bb.experience);
command.Parameters.AddWithValue("#ctc", bb.ctc);
command.Parameters.AddWithValue("#designation", bb.designation);
command.Parameters.AddWithValue("#unithead", bb.unithead);
command.Parameters.AddWithValue("#projectid", bb.projectid);
int rowaffected = command.ExecuteNonQuery();
connection.Close();
if (rowaffected > 0)
{
flag = true;
}
return flag;
}
public bool DeleteEmployee(int bbb)
{
bool flag = false;
string ConnectionString = ;
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_deletemploye";
command.Connection = connection;
command.Parameters.AddWithValue("#id", bbb);
int rowaffected = command.ExecuteNonQuery();
connection.Close();
if (rowaffected > 0)
{ flag = true; }
return flag;
}
public List<ICustomerBO> viewallListsearchBO(int exo)
{
string ConnectionString = "Data Source = ;" +
"Initial Catalog = ;"
+ "User id=;"
+ "Password=password;";
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#id", exo);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_searchemployee";
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int id = Convert.ToInt32(reader["id"]);
string name = reader["employeename"].ToString();
DateTime dob = Convert.ToDateTime(reader["dob"]);
string locn = reader["location"].ToString();
string gender = reader["gender"].ToString();
DateTime doj = Convert.ToDateTime(reader["doj"]);
int exp = Convert.ToInt32(reader["experience"]);
int ctc = Convert.ToInt32(reader["ctc"]);
string desg = reader["designation"].ToString();
string head = reader["unithead"].ToString();
int proj = Convert.ToInt32(reader["projectid"]);
ICustomerBO employee = BOFactory.CustomerBOFactory.ADDEMPLOYEE(id, name, dob, locn, gender, doj, exp, ctc, desg, head, proj);
emplist.Add(employee);
}
connection.Close();
return emplist;
}
}
}
====================================================================================================================================using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BOO;
using DAL;
using Types;
namespace DALFactory
{
public class CustomerDALFactory
{
public static ICustomerDAL addcustomer()
{
ICustomerDAL adddal = new CustomerDAL();
return adddal;
}
public static ICustomerDAL LOGIN()
{
ICustomerDAL obj = new CustomerDAL();
return obj;
}
public static List<ICustomerBO> viewalllist()
{
ICustomerDAL cust=new CustomerDAL();
List<ICustomerBO> cust1 = cust.viewallListBO();
return cust1;
}
public static ICustomerDAL EditCustomer()
{
ICustomerDAL d = new CustomerDAL();
return d;
}
public static ICustomerDAL deletecustomer()
{
ICustomerDAL e = new CustomerDAL();
return e;
}
public static List<ICustomerBO> DBBIND()
{
ICustomerDAL obj5 = new CustomerDAL();
List<ICustomerBO> emp1 = obj5.DBbind();
return emp1;
}
public static List<ICustomerBO> viewsearchlist(int exo)
{
ICustomerDAL cust = new CustomerDAL();
List<ICustomerBO> cust1 = cust.viewallListsearchBO(exo);
return cust1;
}
}
}
============================================================================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Types;
using BOFactory;
using BLLFactory;
using DALFactory;
namespace miniproject
{
public partial class AddEmployee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
if (!IsPostBack)
{
ICustomerBLL bllobj1 = BLLFactory.CustomerBLLFactory.dbind(); //dbind();
List<ICustomerBO> list = bllobj1.dbbind();
DropDownList5.DataSource = list;
DropDownList5.DataTextField = "location";
DropDownList5.DataValueField = "location";
DropDownList5.DataBind();
}
}
protected void TextBox6_TextChanged(object sender, EventArgs e)
{
double a = Convert.ToInt32(TextBox6.Text);
if (a == 0)
{
RangeValidator3.MaximumValue = "3";
RangeValidator3.MinimumValue = "1.5";
RangeValidator3.Type = ValidationDataType.Double;
RangeValidator3.Validate();
if (!RangeValidator3.IsValid)
{
RangeValidator3.ErrorMessage = "Enter CTC between 1.5 and 3";
}
}
else
{
double max = (a * 1.5) + 3;
double min = (a * 1.5) + 1.5;
RangeValidator3.MaximumValue = max.ToString();
RangeValidator3.MinimumValue = min.ToString();
RangeValidator3.Type = ValidationDataType.Double;
RangeValidator3.Validate();
if (!RangeValidator3.IsValid)
{
RangeValidator3.ErrorMessage = "Enter CTC between " + min + " and " + max;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string empname = TextBox1.Text;
DateTime dob = Convert.ToDateTime(TextBox2.Text);
string location = DropDownList5.SelectedItem.Text;
string gender = RadioButtonList3.SelectedItem.Text;
DateTime doj = Convert.ToDateTime(TextBox4.Text);
int experience = Convert.ToInt32(TextBox6.Text);
int ctc = Convert.ToInt32(TextBox5.Text);
string designation = DropDownList4.SelectedItem.Value;
string unithead = DropDownList1.SelectedItem.Text;
int projectid = Convert.ToInt32(DropDownList2.SelectedItem.Text);
ICustomerBLL bllobj = BLLFactory.CustomerBLLFactory.Addcustomer();
ICustomerBO boobj = BOFactory.CustomerBOFactory.Addcustomer( empname,dob, location, gender, doj, experience,ctc,
designation, unithead,projectid);
int rowaffected = bllobj.AddCustomer(boobj);
if(rowaffected>0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "call function", "alert('ADDED SUCCESSFULLY.ID=" + rowaffected + "');", true);
}
else
{
Response.Write("<script>alert('customer not added ')</script>");
}
}
protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void TextBox4_TextChanged(object sender, EventArgs e)
{
}
}
}
================================================================================================================================
</tr>
</table>
</asp:Content>
========================================================================================================================================================
using Types;
using DALFactory;
using BOFactory;
using BLLFactory;
namespace miniproject
{
public partial class EditEmployee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
viewdata();
}
}
private void viewdata()
{
List<ICustomerBO> emp = DALFactory.CustomerDALFactory.viewalllist();
GridView1.DataSource = emp;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
viewdata();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lbid = (Label)GridView1.Rows[e.RowIndex].FindControl("Label1") as Label;
ICustomerBLL bllobj1 = BLLFactory.CustomerBLLFactory.DeleteEmployee();
int id = Convert.ToInt32(lbid.Text);
bool rowaffected = bllobj1.deleteemployee(id);
GridView1.EditIndex = -1;
viewdata();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
viewdata();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
GridViewRow SelectedRow = GridView1.Rows[e.RowIndex];
Label lbid = (Label)SelectedRow.FindControl("Label1") as Label;
string Name = (SelectedRow.FindControl("TextBox1") as TextBox).Text;
DateTime dob = Convert.ToDateTime((SelectedRow.FindControl("TextBox2") as TextBox).Text);
string Location = (SelectedRow.FindControl("TextBox3") as TextBox).Text;
string gender = (SelectedRow.FindControl("TextBox4") as TextBox).Text;
DateTime doj = Convert.ToDateTime((SelectedRow.FindControl("TextBox5") as TextBox).Text);
int exp = Convert.ToInt32((SelectedRow.FindControl("TextBox6") as TextBox).Text);
int ctc = Convert.ToInt32((SelectedRow.FindControl("TextBox7") as TextBox).Text);
string Designation = (SelectedRow.FindControl("TextBox8") as TextBox).Text;
string Headid = (SelectedRow.FindControl("TextBox9") as TextBox).Text;
int projid = Convert.ToInt32((SelectedRow.FindControl("TextBox10") as TextBox).Text);
int id = int.Parse(lbid.Text);
string name = Name.ToString();
DateTime dob1 = Convert.ToDateTime(dob);
string locn = Location.ToString();
string gen = gender.ToString();
DateTime doj1 = Convert.ToDateTime(doj);
int expr = Convert.ToInt32(exp);
int ctc1 = Convert.ToInt32(ctc);
string desg = Designation.ToString();
string head1 = Headid.ToString();
int proj1 = Convert.ToInt32(projid);
ICustomerBO boobj = BOFactory.CustomerBOFactory.EditCustomer(id, name, dob1, locn, gen, doj1, expr, ctc1, desg, head1, proj1);
ICustomerBLL bllobj = BLLFactory.CustomerBLLFactory.EditEmployee();
bool success = bllobj.editemployee(boobj);
GridView1.EditIndex = -1;
viewdata();
}
protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
{
GridViewRow SelectedRow = GridView1.SelectedRow;
Label lbid = (Label)SelectedRow.FindControl("Label1") as Label;
string Name = (SelectedRow.FindControl("Label2") as Label).Text;
DateTime dob = Convert.ToDateTime((SelectedRow.FindControl("Label3") as Label).Text);
string Location = (SelectedRow.FindControl("Label4") as Label).Text;
int projid = Convert.ToInt32((SelectedRow.FindControl("Label11") as Label).Text);
int id = Convert.ToInt32(lbid.Text);
Session["EmployeeID"] = id;
Session["EmployeeName"] = Name;
Session["CTC"] = ctc;
Session["DESIGNATION"] = Designation;
Session["HEADID"] = Headid;
Session["PROJECTID"] = projid;
Response.Redirect("Update.aspx");
}
}
}
==================================================================================================================================
<%# Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="EditEmployee.aspx.cs" Inherits="miniproject.EditEmployee" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceholder1" runat="server">
<div style="margin: left:25%">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged1">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmployeeName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("empname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("empname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DateOfBirth">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("dob") %>'></asp:TextBox>
<asp:CommandField EditText="Select" HeaderText="Action" ShowSelectButton="True" />
<asp:CommandField EditText="Delete" HeaderText="Action" ShowDeleteButton="True" />
<asp:CommandField HeaderText="Action" ShowEditButton="True" />
</Columns>
</asp:GridView>
</div>
</asp:Content>
===================================================================================================================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace DAL
{
public class DBUtility
{
public static SqlConnection getconnection()
{
SqlConnection dbconnection = null;
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["constr"];
if(settings!=null)
{
string str = settings.ConnectionString;
dbconnection = new SqlConnection(str);
}
return dbconnection;
}
}
}
============================================================================================================================
public int updatesupplier(ISupplierBO objBO)
{
int ret = 0;
SqlConnection conn = DBUtility.getconnection();
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_Updatesupplier";
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#Supplierid",objBO.Suplierid);
cmd.Parameters.AddWithValue("#Companyname", objBO.Companyname);
cmd.Parameters.AddWithValue("#Contactname", objBO.Contactname);
cmd.Parameters.AddWithValue("#Companyaddress", objBO.Companyaddress);
cmd.Parameters.AddWithValue("#City", objBO.City);
cmd.Parameters.AddWithValue("#Country", objBO.Country);
cmd.Parameters.AddWithValue("#Homepage", objBO.Homepage);
cmd.Parameters.AddWithValue("#Contactno", objBO.Contactno);
cmd.Parameters.AddWithValue("#Emailaddress", objBO.Emailaddress);
cmd.Parameters.AddWithValue("#Bankdetails", objBO.Bankdetails);
cmd.Parameters.AddWithValue("#Accountno", objBO.Accountno);
ret = cmd.ExecuteNonQuery();
conn.Close();
return ret;
}
======================================================================================================================================
<connectionStrings>
<add name="constr" connectionString="Data Source=sql01;Initial Catalog=dbtemp;User ID=vishal;Password=mahesh" providerName="System.Data.SqlClient"/>
</connectionStrings>
=====================================================================================================================================
<asp:TemplateField HeaderText="UnitHead">
<ItemTemplate>
<asp:Label ID="Label10" runat="server" Text='<%# Eval("unithead") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProjectID">
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Eval("projectid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Label12" runat="server" Text="Enter ID to search"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" OnPageIndexChanging="GridView1_PageIndexChanging" PageIndex="5" AllowPaging="True" PageSize="5">
===================================================================================================================================
using Types;
using DALFactory;
using BOFactory;
namespace miniproject
{
public partial class ViewEmployee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
private void BindData()
{
List<ICustomerBO> emp = DALFactory.CustomerDALFactory.viewalllist();
GridView1.DataSource = emp;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int x = Convert.ToInt16(TextBox1.Text);
List<ICustomerBO> empc = DALFactory.CustomerDALFactory.viewsearchlist(x);
GridView2.DataSource = empc;
GridView2.DataBind();
}
}
}