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();
}
Related
Redesigning an application from a set number of images stored with other items to display, to a variable number of images stored in a second table.
Found this question and have started modifying from it, but am getting a bit lost: ASP.Net Display Images in a GridView span across columns and rows? Using C#
I have the datalist control for asp.net page built, but know the path item will not work:
<asp:DataList ID="dlImages" runat="server"
RepeatColumns ="2"
RepeatDirection ="Horizontal"
RepeatLayout ="Flow">
<ItemTemplate>
<asp:Image ID="ImageQ" runat="server" Width="150px" ImageUrl='<%# Bind("ImageFile", "~/photo/{0}") %>' />
</ItemTemplate>
</asp:DataList>
But am lost trying to get the data into this list.
Originally The image data was loaded along with other information via the below:
protected void Page_Load(object sender, EventArgs e)
{
string sConstr = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
SqlConnection Conn = new SqlConnection(sConstr);
using (Conn)
{
SqlCommand command = new SqlCommand("QuestionDetail", Conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#QuestionID", SqlDbType.BigInt));
command.Parameters["#QuestionID"].Value = Convert.ToInt32(Request["Id"]);
Conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
byte[] imgBytes = (byte[])reader["ImageFile"];
string encodedBytes = Convert.ToBase64String(imgBytes);
string url = string.Concat("data:image/jpg;base64,", encodedBytes);
Image1.ImageUrl = url;
byte[] imgBytes2 = (byte[])reader["ImageFile2"];
string encodedBytes2 = Convert.ToBase64String(imgBytes2);
string url2 = string.Concat("data:image/jpg;base64,", encodedBytes2);
Image2.ImageUrl = url2;
byte[] imgBytes3 = (byte[])reader["ImageFile3"];
string encodedBytes3 = Convert.ToBase64String(imgBytes3);
string url3 = string.Concat("data:image/jpg;base64,", encodedBytes3);
Image3.ImageUrl = url3;
byte[] imgBytes4 = (byte[])reader["ImageFile4"];
string encodedBytes4 = Convert.ToBase64String(imgBytes4);
string url4 = string.Concat("data:image/jpg;base64,", encodedBytes4);
Image4.ImageUrl = url4;
txt_QuestionID.Text = reader["Id"].ToString();
txt_author.Text = reader["Author"].ToString();
txt_Date.Text = reader["SubmitDate"].ToString();
txt_Stem.Text = reader["Stem"].ToString();
txt_RespA.Text = reader["RespA"].ToString();
txt_RespB.Text = reader["RespB"].ToString();
txt_RespC.Text = reader["RespC"].ToString();
txt_RespD.Text = reader["RespD"].ToString();
txt_RespE.Text = reader["RespE"].ToString();
txt_Answer.Text = reader["Answer"].ToString();
txt_Critique.Text = reader["Critique"].ToString();
txt_KeyObjective.Text = reader["KeyObjective"].ToString();
txt_References.Text = reader["References"].ToString();
txt_Practice1.Text = reader["PracticeArea1"].ToString();
txt_Practice2.Text = reader["PracticeArea2"].ToString();
txt_Practice3.Text = reader["PracticeArea3"].ToString();
txt_Practice4.Text = reader["PracticeArea4"].ToString();
txt_IsCloneOf.Text = reader["IsCloneOf"].ToString();
}
reader.Close();
}
}
I have taken the Image portions out and am trying to process them to the DataList via a separate code block (and leave the text elements as is) and have a stored procedure that will grab the applicable records.
This section of the pageload is loading placeholders correctly based on the number of images attached to each question,,, but how to get the encoded image read instead of passing a path.....:
DataTable dt = new DataTable();
using (Conn)
{
SqlCommand ad = new SqlCommand("ImageDetail", Conn);
ad.CommandType = CommandType.StoredProcedure;
ad.Parameters.Add(new SqlParameter("#QuestionID", SqlDbType.BigInt));
ad.Parameters["#QuestionID"].Value = Convert.ToInt32(Request["Id"]);
SqlDataReader reader2 = command.ExecuteReader();
while (reader2.Read())
{
if(!Convert.IsDBNull(reader2["ImageFile"]))
{
byte[] imgBytes = (byte[])reader2["ImageFile"];
string encodedBytes = Convert.ToBase64String(imgBytes);
string url = string.Concat("data:image/jpg;base64,", encodedBytes);
}
}
reader2.Close();
dt.Load(reader2);
}
dlImages.DataSource = dt;
dlImages.DataBind();
Still a total noob, and everytime I change controls it takes me awhile to figure out how to use the new one/s. Right now The code will run with no errors,,, but no images either. I had to add the check for "IsDBNULL" as I kept getting this error. I know that the table being accessed by the ImageDetail Stored Procedure has zero null values in any record, and that the stored procedure returns records when fed a QuestionID.
Was finally able to figure this out.
Datalist control:
<asp:DataList ID="dlImages" runat="server"
RepeatColumns ="2"
RepeatDirection ="Vertical"
CellSpacing ="20"
RepeatLayout ="Table">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="200px" ImageUrl='<%# "GetImage.aspx?id=" + System.Convert.ToString(Eval("ImageID")) %>' /><br />
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ImageName") %>' Font-Bold="True" Font-Size="1.2em" ForeColor="Navy"/><br />
<asp:Label ID="Label2" runat="server" Text='<%# Eval("ImageContent") %>' Font-Italic="true"/><br /> <br />
</ItemTemplate>
DataTable definition for populating (note the datasource is previously defined on the page load event):
DataTable dt = new DataTable();
using (Conn)
{
SqlDataAdapter ad = new SqlDataAdapter("SELECT QuestionID, Images2.ImageID, ImageFile, ImageContent, ImageName, SEQ_NUM from qimages join Images2 on qimages.imageid = images2.imageid where QuestionID = #QuestionID", Conn);
ad.SelectCommand.Parameters.Add("QuestionID", SqlDbType.BigInt).Value = txt_QuestionID.Text;
ad.Fill(dt);
}
dlImages.DataSource = dt;
dlImages.DataBind();
Finally the code for the "GetImage.aspx" page the retrieves and passes the image to the datalist. This page uses only the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sImageID = Request.QueryString["id"];
string constr = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
string sQuery = "SELECT ImageFile from Images2 WHERE ImageID = #ImageID";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(sQuery, con);
cmd.Parameters.Add("#ImageID", SqlDbType.Int).Value = Int32.Parse(sImageID);
using (con)
{
con.Open();
SqlDataReader DR = cmd.ExecuteReader();
if (DR.Read())
{
byte[] imgData = (byte[])DR["ImageFile"];
Response.BinaryWrite(imgData);
}
}
}
}
This is working to display the database encoded images in two columns based on the question being looked at.
Thanks everyone for the pointers.
I have a DropDownList in a GridView and I am wanting to have the selected value be whatever the value for that particular person is in the database
My ASP Code for the DropDownList:
<asp:TemplateField HeaderText="Team" SortExpression="Team">
<ItemTemplate>
<asp:DropDownList ID="ddlTeam" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Team"
DataValueField="Team" ondatabound="ddlTeam_DataBound">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
SelectCommand="SELECT DISTINCT [Team] FROM [Team_Names]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
My ddlTeam_OnBound:
protected void ddlTeam_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
foreach (ListItem item in ddl.Items)
{
if (item.Text == "valor")
{
item.Text = "Team Valor";
}
else if (item.Text == "mystic")
{
item.Text = "Team Mystic";
}
}
}
UPDATE - No Error but DDL is empty:
DropDownList ddl = new DropDownList();
string query2 = "SELECT team_name FROM sec WHERE job = " + TextBox1.Text;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query2, con))
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while(read.Read())
{
ddl.SelectedValue = read["team_name"].ToString();
}
}
con.Close();
}
}
Do everything in a query in SqlDataSource and don't use code behind without necessity.
<asp:TemplateField HeaderText="Team" SortExpression="Team">
<ItemTemplate>
<asp:DropDownList ID="ddlTeam" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Team_txt"
DataValueField="Team"><%--No need ondatabound="ddlTeam_DataBound"--%>
</asp:DropDownList><%--datasourceId must match --%>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
SelectCommand="SELECT DISTINCT [Team],case Team when 'valor' then 'Team Valor' when 'mystic' then 'Team Mystic' else Team end team_txt FROM [Team_Names]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
You aren't executing the SqlCommand or opening a SqlConnection. You should put your input into a parameter to prevent a potential SQL Injection attack.
As an example:
string teamName = string.Empty;
using (SqlConnection connection = new SqlConnection("your connection string"))
{
connection.Open();
string query = "SELECT DISTINCT team_name FROM sec WHERE job = #job";
SqlParameter param = new SqlParameter
{
ParameterName = "#job",
Value = TextBox1.Text
};
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.Add(param);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow);
if (reader.Read())
{
teamName = reader.GetString(0);
// or
int ord = reader.GetOrdinal("team_name");
teamName = reader.GetString(ord); // Handles nulls and empty strings.
}
}
}
EDIT
You also have to set up your drop down list correctly.
DropDownList ddl = new DropDownList();
ddl.DataSource = // call your database code - see above
ddl.DataValueField = "ValueProperty";
ddl.DataTextField = "TextProperty";
ddl.DataBind();
ddl.SelectedValue = teamName;
I've encountered an error which is absolutely driving me insane. Forgive me, I'm a novice, so I may be missing something out which is stupid or silly so sorry in advance.
I keep getting the error
"Procedure or function 'prcPersonalSelectedByPatientIdAppointmentSelect' expects parameter '#PatientNumber', which was not supplied."
This is baffling to me as '#PatientNumber' is in the stored procedure but my knowledge of SQL isn't the greatest.
ASPX Code
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlResults" runat="server" ScrollBars="Auto" >
<asp:GridView ID="gvAppointmentSearch" runat="server" Font-Names = "Arial"
Font-Size = "11pt" ForeColor = "#000000"
onselectedindexchanged="gvAppointmentSearch_SelectedIndexChanged"
AutoGenerateColumns = "false" DataKeyNames="PatientNumber" AllowPaging = "true"
OnPageIndexChanging = "OnPaging" PageSize = "10" Width = "100%"
HeaderStyle-BackColor = "#465c71" HeaderStyle-ForeColor = "#ffffff"
style="margin-bottom: 26px">
<Columns>
<%--Creates a select button that appear at the start of the grid view--%>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Select" ID="lnkSelect" runat="server" CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Appointment Number" ItemStyle-Wrap="False">
<ItemTemplate>
<%--This will be the first field to appear beside the select button--%>
<asp:Label ID="lblAppointmentNumber" Text='<%# Eval("AppointmentNumber") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<%--Bound fields will place them in a specific order--%>
<asp:BoundField DataField = "AppointmentDate" HeaderText = "Appointment Date" DataFormatString="{0:d}" />
<asp:BoundField DataField = "AppointmentTime" HeaderText = "Appointment Time" DataFormatString="{0:d}" />
<asp:BoundField DataField = "Consultant" HeaderText="Referred By" ItemStyle-Wrap="False" />
<asp:BoundField DataField = "ByAttendance" HeaderText="Attendance"/>
</Columns>
</asp:GridView>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvAppointmentSearch" />
</Triggers>
</asp:UpdatePanel>
C# Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Populate dropdown if no record has been selected
String strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strConString);
conn.ConnectionString = strConString;
SqlCommand cmdInit = new SqlCommand();
cmdInit.CommandText = "Select * from DropdownCounty";
cmdInit.Connection = conn;
conn.Open();
DataTable dtInit = new DataTable();
dtInit.Load(cmdInit.ExecuteReader());
conn.Close();
dpdCounty.DataSource = dtInit;
dpdCounty.DataTextField = "County";
dpdCounty.DataValueField = "CountyID";
dpdCounty.DataBind();
DataSet ds = new DataSet();
ds = (DataSet)Session["DS"];
this.DataBindSearch();
try
{
//Fields that are required to be filled in if the information is avaliable
patientNumber.Text = ds.Tables[0].Rows[0]["PatientNumber"].ToString();
txtHCNumber.Text = ds.Tables[0].Rows[0]["HC_Number"].ToString();
//if (ds.Tables[0].Rows[0]["ConsentToDatabase"].ToString() != null)
//chkDBConsent.Checked = (bool)ds.Tables[0].Rows[0]["ConsentToDatabase"];
if (ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString() != "dd/mm/yyyy")
{
if (ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString() != null && ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString() != "")
{
ConsentGivenDate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString()).ToShortDateString();
}
}
IDnumberLegacy.Text = ds.Tables[0].Rows[0]["ID_Number_LegacyID"].ToString();
if (ds.Tables[0].Rows[0]["Sex"] != DBNull.Value)
{
//Datasource is added only when values are being added to allow for alterations to be made
//Allows for records with older dropdown values no longer selectable to be visible
String strConnString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.ConnectionString = strConnString;
SqlCommand cmd = new SqlCommand();
SqlCommand cmdPop = new SqlCommand();
cmd.CommandText = "Select Sex from DropdownSex";
cmd.Connection = con;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
con.Close();
//String builder to gather records that are currently active
StringBuilder currentid = new StringBuilder();
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
currentid.AppendLine(string.Join(",", dr.ItemArray));
}
//convert stringbuilder to string
var output = currentid.ToString();
// Creates new StringReader instance from System.IO
using (StringReader reader = new StringReader(output))
{
// Loop over the lines in the string.
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
count++;
if (line == (ds.Tables[0].Rows[0]["Sex"].ToString()))
cmdPop.CommandText = " Select * From DropdownSex";
}
}
if (cmdPop.CommandText == "")
cmdPop.CommandText = " Select * From DropdownSex";
cmdPop.Connection = con;
con.Open();
DataTable dtValues = new DataTable();
dtValues.Load(cmdPop.ExecuteReader());
con.Close();
dpdSex.DataSource = dtValues;
dpdSex.DataTextField = "Sex";
dpdSex.DataValueField = "SexID";
dpdSex.DataBind();
dpdSex.SelectedValue = ds.Tables[0].Rows[0]["SexID"].ToString();
}
txtPatientFirstName.Text = ds.Tables[0].Rows[0]["Forename"].ToString();
txtPatientSurname.Text = ds.Tables[0].Rows[0]["Surname"].ToString();
PatientMaiden.Text = ds.Tables[0].Rows[0]["MaidenName"].ToString();
if (ds.Tables[0].Rows[0]["DateOfBirth"].ToString() != "dd/mm/yyyy")
{
if (ds.Tables[0].Rows[0]["DateOfBirth"].ToString() != null && ds.Tables[0].Rows[0]["DateOfBirth"].ToString() != "")
{
txtDateOfBirth.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["DateOfBirth"].ToString()).ToShortDateString();
}
}
AddressLine1.Text = ds.Tables[0].Rows[0]["AddressLine1"].ToString();
AddressLine2.Text = ds.Tables[0].Rows[0]["AddressLine2"].ToString();
AddressLine3.Text = ds.Tables[0].Rows[0]["AddressLine3_TownCity"].ToString();
AddressLine4.Text = ds.Tables[0].Rows[0]["AddressLine4_Region"].ToString();
if (ds.Tables[0].Rows[0]["County"] != DBNull.Value)
{
//Datasource is added only when values are being added to allow for alterations to be made
//Allows for records with older dropdown values no longer selectable to be visible
String strConnString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.ConnectionString = strConnString;
SqlCommand cmd = new SqlCommand();
SqlCommand cmdPop = new SqlCommand();
cmd.CommandText = "Select County from DropdownCounty";
cmd.Connection = con;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
con.Close();
//String builder to gather records that are currently active
StringBuilder currentid = new StringBuilder();
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
currentid.AppendLine(string.Join(",", dr.ItemArray));
}
//convert stringbuilder to string
var output = currentid.ToString();
// Creates new StringReader instance from System.IO
using (StringReader reader = new StringReader(output))
{
// Loop over the lines in the string.
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
count++;
if (line == (ds.Tables[0].Rows[0]["County"].ToString()))
cmdPop.CommandText = " Select * From DropdownCounty";
}
}
if (cmdPop.CommandText == "")
cmdPop.CommandText = " Select * From DropdownCounty";
cmdPop.Connection = con;
con.Open();
DataTable dtValues = new DataTable();
dtValues.Load(cmdPop.ExecuteReader());
con.Close();
dpdCounty.DataSource = dtValues;
dpdCounty.DataTextField = "County";
dpdCounty.DataValueField = "CountyID";
dpdCounty.DataBind();
dpdCounty.SelectedValue = ds.Tables[0].Rows[0]["CountyID"].ToString();
}
PostCode.Text = ds.Tables[0].Rows[0]["PostCode"].ToString();
HomeTelNumber.Text = ds.Tables[0].Rows[0]["HomeTelNumber"].ToString();
MobileTelNumber.Text = ds.Tables[0].Rows[0]["MobileTelNumber"].ToString();
WorkTelNumber.Text = ds.Tables[0].Rows[0]["WorkTelNumber"].ToString();
PatientEmail.Text = ds.Tables[0].Rows[0]["Email"].ToString();
PatientNotes.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
//Sets the color of the text box depedning if a value has been entered
string hex = "#F0F8FF";
if (txtDateOfBirth.Text != "dd/mm/yyyy")
txtDateOfBirth.ForeColor = System.Drawing.Color.Black;
else
txtDateOfBirth.BackColor = System.Drawing.ColorTranslator.FromHtml(hex);
if (ConsentGivenDate.Text != "dd/mm/yyyy")
ConsentGivenDate.ForeColor = System.Drawing.Color.Black;
else
ConsentGivenDate.BackColor = System.Drawing.ColorTranslator.FromHtml(hex);
}
//If the dataset is empty this is executed instead
catch (Exception fe)
{
lblErrors.Text = "New Record Successfully Started!";
//calls the poup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
}
}
//Not required as this label has been replaced with a popup, still used to store message that will be displayed
lblErrors.Visible = true;
//Load the initial data from the session once
//***Custom error messages below***//
//Used to pull error message if someone else has already updated the data first
if (Session["ex"] != null)
{
var msg = Session["ex"].ToString();
//Message to be displayed
if (msg == "Error")
lblErrors.Text = "Update Failed! Someone has already made changes!";
else
lblErrors.Text = "Unable to update HC Number!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["ex"] = null;
}
//As the page refreshes when a new record is added to allow the master page to display the new records details this is required to pull
//forward the success message to inform the user that the record has been added and the page has not just refreshed
if (Session["NewRecordAdded"] != null)
{
//Message to be displayed
lblErrors.Text = "Record Succesfully Added!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["NewRecordAdded"] = null;
}
//Error when trying to find record that does not exist
if (Session["FindRecordError"] != null)
{
string a = Session["FindRecordError"].ToString();
//Message to be displayed
if (a == "Unable to locate")
lblErrors.Text = "Unable to find record!";
else
lblErrors.Text = "Full HC Number required!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["FindRecordError"] = null;
}
if (Session["PersonalDeatilsSave"] != null)
{
//only if an update has occured
lblErrors.Text = "Save Successful!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["PersonalDeatilsSave"] = null;
}
}
protected void gvAppointmentSearch_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
int index = gvAppointmentSearch.SelectedIndex;
string strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConString);
myConnect.ConnectionString = strConString;
string strCommandText = "prcPersonalSelectedByPatientIdAppointmentRetrieve";
try
{
SqlCommand sqlCmd = new SqlCommand(strCommandText, myConnect);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add(new SqlParameter("#PatientNumber", gvAppointmentSearch.DataKeys[index].Value.ToString()));
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlCmd;
da.Fill(ds, "personal");
//Needed to reset the clinical eval page for newly selected patient
Session["NDS"] = null;
}
catch (Exception fe)
{
lblMoreErrors.Text = "Error: " + fe.Message;
}
try
{
//Assigns the selected patients details to the dataset and redirects the user to the personal page
Session["DS"] = ds;
Response.Redirect("~/UserPages/PatientAppointment.aspx");
}
catch (Exception er)
{
lblErrors.Text = "Error: " + er.Message;
}
}
//Tells the gridview what to do when the page change is selected
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
this.DataBindSearch();
gvAppointmentSearch.PageIndex = e.NewPageIndex;
gvAppointmentSearch.DataBind();
}
protected void DataBindSearch()
{
DataSet ds = new DataSet();
string strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConString);
myConnect.ConnectionString = strConString;
string strCommandText = "prcPersonalSelectedByPatientIdAppointmentSelect";
try
{
SqlCommand sqlCmd = new SqlCommand(strCommandText, myConnect);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlCmd;
da.Fill(ds, "personal");
gvAppointmentSearch.DataSource = ds;
//Finally, all results matching the criteria will be placed into the gridview
gvAppointmentSearch.DataBind();
DataTable dt = new DataTable();
da.Fill(dt);
Session["CurrentData"] = dt;
//Counts the number of results found
lblResults.Text = "Results Found: " + ds.Tables.Cast<DataTable>().Sum(x => x.Rows.Count).ToString();
}
catch (Exception fe)
{
lblErrors.Text = "Error: " + fe.Message;
}
}
}
SQL Stored Procedure
ALTER PROCEDURE [dbo].[prcPersonalSelectedByPatientIdAppointmentSelect]
#PatientNumber int
AS
SELECT
[dbo].[Appointments].[AppointmentDate] as AppointmentDate
,dbo.Appointments.AppointmentTime as AppointmentTime
,[dbo].[DropdownReferredBy].[ReferredBy] as Consultant
,[dbo].[DropdownAttended].[ByAttendance] as ByAttendance
,dbo.Appointments.AppointmentNumber as AppointmentNumber
FROM [dbo].[PATIENTS]
LEFT JOIN dbo.Appointments on dbo.PATIENTS.PatientNumber = dbo.Appointments.PatientNumber
LEFT JOIN [dbo].[DropdownReferredBy] on dbo.Appointments.ReferredBy = [dbo].[DropdownReferredBy].ReferredBy
LEFT JOIN [dbo].[DropdownAttended] on dbo.Appointments.ByAttendance = dbo.DropdownAttended.ByAttendance
WHERE dbo.PATIENTS.PatientNumber LIKE #PatientNumber
ORDER BY AppointmentNumber ASC;
To add to all this, this page takes its data from another gridview with a connecting stored procedure.
Thanks in advance and sorry if I've done something very silly!!!
In your DataBindSearch() method, you are not providing a value for the #PatientNumber parameter. You need to specify that parameter and give it a value like you do further up in your code.
Also, while I have your attention, you should really be putting your SqlConnection and SqlCommand objects in using statements.
protected void DataBindSearch()
{
DataSet ds = new DataSet();
string strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
string strCommandText = "prcPersonalSelectedByPatientIdAppointmentSelect";
using (SqlConnection myConnect = new SqlConnection(strConString))
using (SqlCommand sqlCmd = new SqlCommand(strCommandText, connect))
{
try
{
SqlCommand sqlCmd = new SqlCommand(strCommandText, myConnect);
sqlCmd.CommandType = CommandType.StoredProcedure;
//You need to add the parameter before you call da.Fill()
sqlCmd.Parameters.Add(new SqlParameter("#PatientNumber", /*Parameter Value*/));
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlCmd;
da.Fill(ds, "personal");
gvAppointmentSearch.DataSource = ds;
//Finally, all results matching the criteria will be placed into the gridview
gvAppointmentSearch.DataBind();
DataTable dt = new DataTable();
da.Fill(dt);
Session["CurrentData"] = dt;
//Counts the number of results found
lblResults.Text = "Results Found: " + ds.Tables.Cast<DataTable>().Sum(x => x.Rows.Count).ToString();
}
catch (Exception fe)
{
lblErrors.Text = "Error: " + fe.Message;
}
}
}
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
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();
}
}