I am using .net and I am changing my .aspx.cs file to add the user choice in radio button to a row in database.
private DataSet CreateData()
{
DataTable table = new DataTable();
table.Columns.Add(new DataColumn("OptionID", System.Type.GetType("System.String")));
table.Columns.Add(new DataColumn("Option", System.Type.GetType("System.String")));
DataRow row1 = table.NewRow();
row1["OptionID"] = "1";
row1["Option"] = "option 1";
DataRow row2 = table.NewRow();
row2["OptionID"] = "2";
row2["Option"] = "two";
DataRow row3 = table.NewRow();
row3["OptionID"] = "3";
row3["Option"] = "three";
table.Rows.Add(row1);
table.Rows.Add(row2);
table.Rows.Add(row3);
DataSet ds = new DataSet();
ds.Tables.Add(table);
return ds;
}
private void bindRadioList()
{
DataSet ds = CreateData();
RadioButtonList1.DataSource = ds;
RadioButtonList1.DataTextField = "Option";
RadioButtonList1.DataValueField = "OptionID";
RadioButtonList1.DataBind();
if (RadioButtonList1.Items.Count > 0)
RadioButtonList1.Items[0].Selected = true; //you can set a selected items you want.
}
public void Button1_Click(object sender, System.EventArgs e)
{
Session["choice"] = RadioButtonList1.SelectedValue;
}
But I do not know how could I get this value at my last step when people click submit at the next page.
I tried:
string sqlIns = "INSERT INTO Choice (Email, Choice) VALUES (#Email, #Choice)";
SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
conn.Open();
try
{
SqlCommand cmdIns = new SqlCommand(sqlIns, conn);
cmdIns.Parameters.Add("#Email", userRecord.email);
cmdIns.Parameters.Add("#Choice", (string)Session["choice"]);
cmdIns.ExecuteNonQuery();
But I got this error:
Exception Details: System.Data.SqlClient.SqlException: The
parameterized query '(#Email nvarchar(19),#Choice
nvarchar(4000))INSERT INTO Choice (' expects the parameter '#Choice',
which was not supplied.
Use AddWithValue instead of Add like;
cmdIns.Parameters.AddWithValue("#Email", userRecord.email);
cmdIns.Parameters.AddWithValue("#Choice", (string)Session["choice"]);
From it's documentation;
SqlParameterCollection.Add Method (String, Object) overload has been
deprecated. Use AddWithValue(String parameterName, Object value)
instead. http://go.microsoft.com/fwlink/?linkid=14202"
Or you can use (String, SqlDbType) overload (which I almost always prefer instead of AddWithValue) of Add method like (I assume both your column is NVarChar type);
cmdIns.Parameters.Add("#Email", SqlDbType.NVarChar).Value = userRecord.email;
cmdIns.Parameters.Add("#Choice", SqlDbType.NVarChar).Value = (string)Session["choice"];
Also use using statement to dispose your SqlConnection adn SqlCommand like;
using(SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]))
using(SqlCommand cmdIns = conn.CreateCommand())
{
cmdIns.CommandText = sqlIns;
...
...
}
please check your store procedure where you are passing paramerters there you are not passing parameters #Choice
I found out the problem and solution for this:
The problem is Session["choice"] = Null and it is not acceptable under MSN standard. So I need to add this to prevent Null value :
if ((string)Session["choice"] == null)
{
cmdIns.Parameters.Add("#Choice", SqlDbType.NVarChar).Value = DBNull.Value;
}
else
{
// cmdIns.Parameters.AddWithValue("#Choice", (string)Session["choice"]);
cmdIns.Parameters.Add("#Choice", SqlDbType.NVarChar).Value = (string)Session["choice"];
}
To fix the null value, in .aspx file(I still can't figure out why the old code give null, but this one can avoid it)
<div>
<asp:RadioButton ID="RadioButton1" GroupName="Group1" Text="Choice 1" OnCheckedChanged="Button1_Click" AutoPostBack="true" runat="server" />
<asp:RadioButton ID="RadioButton2" GroupName="Group1" Text="Choice 2" OnCheckedChanged="Button1_Click" AutoPostBack="true" runat="server" />
<asp:RadioButton ID="RadioButton3" GroupName="Group1" Text="Choice 3" OnCheckedChanged="Button1_Click" AutoPostBack="true" runat="server" />
</div>
and .cs file:
protected void Button1_Click(object sender, System.EventArgs e)
{
// Session["choice"] = RadioButtonList1.SelectedItem.Text;
if (RadioButton1.Checked)
{
Session["choice"] = "Choice 1";
}
if (RadioButton2.Checked)
{
Session["choice"] = "Choice 2";
}
if (RadioButton3.Checked)
{
Session["choice"] = "Choice 3";
}
}
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();
}
After some lengthy experimentation, I discovered that having this line of code on the aspx side:
<EditItemTemplate>
<asp:DropDownList ID="ddl_Project_Owner" runat="server" Width="70px"
DataTextField="Project_Owner" DataValueField="Project_Owner"
SelectedValue='<%# Bind("Project_Owner") %>' >
</asp:DropDownList>
</EditItemTemplate>
caused an index error, but removing the SelectedValue='<%# Bind("Project_Owner") %>' piece allowed the gridview to function properly. The only thing is, when the row goes into edit mode, the dropdown is not filled with the current value. It's blank. I'd like to fill it with the current value.
On the code-behind side, I use this code to fill the dropdown:
protected void DataGrid_ResourceAllocation_EditCommand(object sender, GridViewEditEventArgs e)
{
DataGrid_ResourceAllocation.EditRowStyle.BackColor = System.Drawing.Color.LightYellow;
DataGrid_ResourceAllocation.EditIndex = e.NewEditIndex;
LoadResourceAllocationGrid();
//DataGrid_ResourceAllocation.DataBind();
SqlConnection conn = GetConnection();
int RAC = DataGrid_ResourceAllocation.Rows.Count;
GridViewRow row = DataGrid_ResourceAllocation.Rows[e.NewEditIndex];
//*********************************************************
//******** Fill in all your dropdown lists here ***********
//*********************************************************
DropDownList ddList = row.FindControl("ddl_Project_Owner") as DropDownList;
string ddListVal = ddList.SelectedValue;
//DropDownList ddList = (DropDownList)e.Row.FindControl("ddl_Project_Owner");
if (ddList != null)
{
//bind dropdown-list
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
//DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = ddListVal;
}
}
I tried that "ddListVal" variable because I thought it might work, but it didn't, so you can ignore that.
Can anyone help me get my dropdown to populate with the current value that exists for that field in that record?
This error is due to this : you set selectedValeue befor binding dropdownlist.
you can bind dropdownlist in RowDataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddList= e.Row.FindControl("ddl_Project_Owner") as DropDownList;
if (ddList != null)
{
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
}
}
}
I am applying search using a textbox and button and results are shown in GridView in ASP.NET. If result do not match with the search then I want that the Label1 "your search do not match" should be visible.
Here is issue that if search result do not match, Label1 is not called.
the code is given below:
SqlConnection con4 = new SqlConnection("Data Source=***; Initial Catalog=***;Integrated Security=***;");
SqlCommand cmd4 = new SqlCommand("select newsid, title, thumbnail,imagepath,imagename from addnews where (title like'%" + TextBox1.Text.ToString() + "%')", con4);
SqlDataAdapter sda4 = new SqlDataAdapter(cmd4);
DataTable dt4 = new DataTable();
sda4.Fill(dt4);
if (dt4 != null)
{
GridView3.DataSource = dt4;
GridView3.DataBind();
}
else
{
Label1.Visible = true;
}
ASPX markup
<asp:Label ID="Label1" runat="server" ForeColor="Red" Text="Search do not match" Visible="False"></asp:Label>
<asp:GridView ID="GridView3" runat="server"> </asp:GridView>
Refer the below code:
DataTable dt4 = new DataTable();
sda4.Fill(dt4);
if (dt4.Rows.Count > 0)
{
GridView3.DataSource = dt4;
GridView3.DataBind();
}
else
{
Label1.Visible = true;
}
You check for dt4 != null, which will always be true because you initialize it as new Datatable(), so it will never go the "else" part of your statement, but simple put an empty dt4 in the source.
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 want to have a label and checkbox for each row in from my query.
I needed to get the number of records from my sql query, but I read that SELECT statements will not work with int numberOfRecords = sqlCmd2.ExecuteNonQuery();. So what should I do instead to get the number of records selected from my query (see code below)?
Is this code enough to do what I need to generate labels and checkboxes from a db? Or am I missing something?
Side Note: I do not want to use the Repeater Control. I have tried it, and it isn't robust enough as I program more complicated pages.
ASP
<table>
<tr>
<td>
<asp:Label ID="LabelFormFields" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:CheckBoxList ID="CheckBoxListFormFields" runat="server">
</asp:CheckBoxList>
</td>
</tr>
</table>
C#
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
{
sqlConn2.Open();
using (SqlCommand sqlCmd2 = new SqlCommand())
{
sqlCmd2.Connection = sqlConn2;
sqlCmd2.CommandType = System.Data.CommandType.Text;
sqlCmd2.CommandText = string.Format("SELECT DisplayName FROM FormField WHERE EventId = 1 AND Visible = 0 ORDER BY ColumnOrder ASC;");
sqlCmd2.ExecuteNonQuery();
int numberOfRecords = //something here;
using (SqlDataReader sqlReader = sqlCmd2.ExecuteReader())
{
while (sqlReader.Read())
{
for (int i = 0; i < numberOfRecords; i++)
{
var PanelFormFields = new Panel();
var LabelFormFields = new Label();
var ListItemFormFields = new ListItem();
LabelFormFields.Text = sqlReader["DisplayName"].ToString();
CheckBoxListFormFields.Items.Add(new ListItem(sqlReader["DisplayName"].ToString(), "C"));
PanelFormFields.Controls.Add(LabelFormFields);
PanelFormFields.Controls.Add(CheckBoxListFormFields);
}
}
}
sqlConn2.Close();
}
}
}
int numberOfRecords = sqlCmd2.ExecuteNonQuery(); //you will get the record numbers; https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
But you don't need the numbers here.
your while (sqlReader.Read()) will help to to control the bounds of loop. Based on your description, you don't need this reader. just fill a datatable, then assign it to a datagrid control. as per you want to display a checkbox for each line, you need to make a custom column.
Here is a good sample about how to implement a checkbox and a label in datagrid: http://www.codeproject.com/Articles/7629/Using-CheckBoxes-within-the-DataGrid-control-to-se
use DataTable.Load(IDataReader reader) method to fill a DataTable and then use DataTable.Rows.Count to get number of Records. change your code to something like this:
.
.
sqlCmd2.CommandType = System.Data.CommandType.Text;
sqlCmd2.CommandText = string.Format("SELECT DisplayName FROM FormField WHERE EventId = 1 AND Visible = 0 ORDER BY ColumnOrder ASC;");
int numberOfRecords;
using (System.Data.DataTable dataTable =new System.Data.DataTable())
{
dataTable.Load(sqlCmd2.ExecuteReader());
numberOfRecords = dataTable.Rows.Count;
for (int i = 0; i < dataTable.Rows.Count; i++)
{
System.Data.DataRow dr = dataTable.Rows[i];
var PanelFormFields = new Panel();
var LabelFormFields = new Label();
var ListItemFormFields = new ListItem();
LabelFormFields.Text = dr["DisplayName"].ToString();
CheckBoxListFormFields.Items.Add(new ListItem(dr["DisplayName"].ToString(), "C"));
PanelFormFields.Controls.Add(LabelFormFields);
PanelFormFields.Controls.Add(CheckBoxListFormFields);
}
}
Here is one answer. Please note that I put the code in the Page_Init rather than Page_Load because the Page_Load reloads with every postback and any changes that were not yet written to the database could go away.
protected void Page_Init(object sender, EventArgs e)
{
DataTable dt = GetData();
//int numberOfRecords = dt.Rows.Count;
foreach (DataRow row in dt.Rows)
{
var PanelFormFields = new Panel();
var LabelFormFields = new Label();
var ListItemFormFields = new ListItem();
LabelFormFields.Text = row[0].ToString();
CheckBoxListFormFields.Items.Add(new ListItem(row[0].ToString(), "C"));
PanelFormFields.Controls.Add(LabelFormFields);
PanelFormFields.Controls.Add(CheckBoxListFormFields);
}
}
private DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
{
sqlConn2.Open();
string sql = string.Format("SELECT DisplayName FROM FormField WHERE EventId = 1 AND Visible = 0 ORDER BY ColumnOrder ASC;");
using (SqlCommand sqlCmd2 = new SqlCommand(sql, sqlConn2))
{
using (SqlDataAdapter da = new SqlDataAdapter(sqlCmd2))
{
da.Fill(dt);
}
}
}
return dt;
}
Also note that I refactored to use a GetData() method to retrieve the DataTable object and simplify the Page_Init method. I did not close the sqlConn2 object because the using block does this for me. I also used a DataAdapter because it is a simple, fast way to fill a table. Finally, while I kept the numberOfRecords in a commented line to show you how you can get the count, if you need it, it is commented because the foreach loop doesn't need this value.