Formatting dynamic dropdownlist text (money) - c#

I am trying to format the text of my drop down list but nothing seems to work. Here is my code below:
Drop down list:
<asp:DropDownList runat="server" ID="ddlSalary" CssClass="ddlBox"
CausesValidation="true" AutoPostBack="true"
onselectedindexchanged="ddlSalary_SelectedIndexChanged" />
Code behind:
if (!IsPostBack)
{
ddlSalary.DataSource = Placements.DropDownPopulating("Placement_Salary_From");
ddlSalary.DataBind();
ddlSalary.Items.Insert(0, new ListItem("-- Salary --", "0"));
Results:
6.0000
200.0000
1000.0000
But I would like:
£6
£200
£1000
I have tried using:
ddlSalary.DataTextFormatString = "{0:C}";
EDIT
Populating drop down list:
public static List<string> DropDownPopulating(string selectedFilter)
{
List<string> returnVal = new List<string> { };
using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["websiteContent"].ConnectionString))
{
sqlCon.Open();
string SQL = "SELECT DISTINCT " + selectedFilter + " FROM Placements";
using (var CMD = new SqlCommand(SQL, sqlCon))
{
using (var DR = CMD.ExecuteReader())
{
while (DR.Read())
{
returnVal.Add(DR[selectedFilter].ToString());
}
}
}
sqlCon.Close();
}
return returnVal;
}

You should use a numeric datatype if you want the formatting to work:
public static List<T> DropDownPopulating<T>(string selectedFilter)
{
var returnVal = new List<T>();
var connectionString = ConfigurationManager.ConnectionStrings["websiteContent"].ConnectionString;
using (var con = new SqlConnection(connectionString))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT DISTINCT " + selectedFilter + " FROM Placements";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// if you are using .NET 4.5
returnVal.Add(reader.GetFieldValue<T>(reader.GetOrdinal(selectedFilter)));
// if you are using .NET 4.0 or older:
// returnVal.Add((T)reader.GetValue(reader.GetOrdinal(selectedFilter)));
}
}
}
return returnVal;
}
and then:
ddlSalary.DataSource = Placements.DropDownPopulating<decimal>("Placement_Salary_From");
ddlSalary.DataTextFormatString = "{0:C}";
ddlSalary.DataBind();

use this query to get data.....
select '$'+Cast((Cast(Price as int))as varchar) from TableName

Related

use System.Data.SQLite to read a row, get data from a few columns, add to a list of objects, loop to the next row

it IS getting data from the DB but what renders on the blazor end of things is the LAST row 13 times(that's actually the number of records in that table).
my simple class
public class ExportedFromDB
{
public string Id;
public string ExportType;
public string Path;
public long Size;
}
the method:
public List<ExportedFromDB> TalkToDBAndGetTheExportMetadata(string jobID)
{
ExportedFromDB exportedFromDB = new ExportedFromDB();
var list = new List<ExportedFromDB>();
int total;
var dbPath = "c:\\ProgramData\\StorageQuest\\Rook Archive\\Jobs\\" + jobID + ".sqlite";
var conn = new SQLiteConnection("Data Source=" + dbPath + ";Version=3;");
using (var cmd = new SQLiteCommand(conn))
{
using (var command = new SQLiteCommand(conn))
{
conn.Open();
command.CommandText = "SELECT * FROM Exported";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
exportedFromDB.Id = reader["Id"].ToString();
exportedFromDB.ExportType = reader["ExportType"].ToString();
exportedFromDB.Path = reader["Path"].ToString();
exportedFromDB.Size = (long)reader["Size"];
list.Add(exportedFromDB);
}
}
conn.Close();
}
}
return list;
}
in my Index.razor file:
<div class="RookJobBlockRight">
#foreach (var exported in rookDashboardExtras.TalkToDBAndGetTheExportMetadata(job.ObjectId))
{
<p>exprt: #exported.Path</p>
}
</div>
Expecting to generate a list of objects and to render the values from each of the objects in said list into my GUI.
Sorry. I realized after I need to add a new object each time a record was read/added to the list.
new method:
public List<ExportedFromDB> TalkToDBAndGetTheExportMetadata(string jobID)
{
ExportedFromDB exportedFromDB = new ExportedFromDB();
var list = new List<ExportedFromDB>();
int total;
var dbPath = "c:\\ProgramData\\StorageQuest\\Rook Archive\\Jobs\\" + jobID + ".sqlite";
var conn = new SQLiteConnection("Data Source=" + dbPath + ";Version=3;");
using (var cmd = new SQLiteCommand(conn))
{
using (var command = new SQLiteCommand(conn))
{
conn.Open();
command.CommandText = "SELECT * FROM Exported";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
list.Add(new ExportedFromDB
{
Id = reader["Id"].ToString(),
ExportType = reader["ExportType"].ToString(),
Path = reader["Path"].ToString(),
Size = (long)reader["Size"]
});
}
}
conn.Close();
}
}
return list;
}

Add string array to SQL query

I have a string array which consists of identifiers. I want to get some values from SQL using these identifiers . Is there a way of adding them with a string value to SqlCommand parameters?
I want to create a query like:
select CaseList from MasterReportData where Id = 1 OR Id = 2 OR Id = 3
This is my C# code:
public static List<string> GetCaseList(string[] masterIdList)
{
try
{
string query = " select CaseList from MasterReportData where #masterId";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("masterId", ***);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(reader[0].ToString());
}
}
conn.Close();
}
catch (Exception e)
{
var err= 0;
}
return list;
}
There are many different ways you can go about doing this but I prefer to create a temp table of possible values. That way you can do something like
select CaseList from MasterReportData where Id IN(select Id from tempTable)
The best approach (with sql optimization) would be:
Create your Type:
CREATE TYPE dbo.IntTTV AS TABLE
( Id int )
Your Ids:
var ids = new List<int>
{
1,
2,
3,
}
Create a schema:
var tableSchema = new List<SqlMetaData>(1)
{
new SqlMetaData("Id", SqlDbType.Int) // I think it's Int
}.ToArray();
Create the table in C#
var table = ids
.Select(i =>
{
var row = new SqlDataRecord(tableSchema);
row.SetInt32(0, i);
return row;
})
.ToList();
Create the SQL Parameter
var parameter = new SqlParameter();
parameter.SqlDbType = SqlDbType.Structured;
parameter.ParameterName = "#Ids";
parameter.Value = table;
parameter.TypeName = "dbo.IntTTV";
var parameters = new SqlParameter[1]
{
parameter
};
Slightly change your query (this is just an example:)
string query = "select mrd.CaseList from MasterReportData mrd"
+ " inner join #ids i on mrd.Id = i.id";
public static List<string> GetCaseList(string[] masterIdList)
{
List<string> list = new List<string>();
try
{
string query = "select CaseList from MasterReportData where ";
using (SqlConnection conn = new SqlConnection(connString))
{
int i = 0;
SqlCommand cmd = new SqlCommand(query, conn);
for(i = 0; i < masterIdList.Length; i++)
{
var parm = "#ID" + i;
cmd.Parameters.Add(new SqlParameter(parm, masterIdList[i]));
query += (i > 0 ? " OR " : "") + " Id = " + parm;
}
cmd.CommandText = query;
//cmd.Parameters.AddWithValue("masterId", ***);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(reader[0].ToString());
}
}
}
}
catch (Exception e)
{
e.ToString();
}
return list;
}

First item of the Dropbox is not working when the page first load using C#

The first item of the Dropbox is not working when the page loaded but if select the second item in the Dropbox the form will populate with the relevant data. If I come back to first item selected previously it will work this time. Any help please. Thanks
HTML code
<asp:DropDownList ID="DropDownListUpdateSample" runat="server" Height="37px" Width="132px" CssClass="auto-style111" AutoPostBack = "true" OnSelectedIndexChanged="DropDownListUpdateSample_SelectedIndexChanged" AppendDataBoundItems="False">
C# Code
//Code to populate the Dropbox
using (SqlCommand cmd5 = new SqlCommand(#"SELECT Patient.MBID, Sample.SampleID
FROM Patient INNER JOIN
Sample ON Patient.MBID = Sample.MBID
WHERE
Patient.Surname = #Surname and Patient.DOB = convert(datetime, #DOB, 103)
ORDER by Sample.SampleID ASC ", con))
{
cmd5.Parameters.AddWithValue("#Surname", txtSearchSurname.Text);
cmd5.Parameters.AddWithValue("#DOB", txtSearchDOB.Text);
SqlDataAdapter da5 = new SqlDataAdapter(cmd5);
DataSet dt5 = new DataSet();
da5.Fill(dt5, "Sample");
DataTable myDataTable = dt5.Tables[0];
// Loop to insert the Sample ID in the Drop box
foreach (DataRow tempRow_Variable in myDataTable.Rows)
{
var tempRow = tempRow_Variable;
DropDownListUpdateSample.Items.Add(tempRow["SampleID"].ToString());
}
}
//Code to Populate the form after an item is selected from the Dropbox
protected void DropDownListUpdateSample_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
{
con.Open();
using (SqlCommand st = new SqlCommand(#"SELECT *
FROM Sample
WHERE
SampleID=#SampleID", con))
{
st.Parameters.AddWithValue("#SampleID", DropDownListUpdateSample.SelectedItem.Value);
using (SqlDataReader reader = st.ExecuteReader())
{
while (reader.Read())
{
txtUpdateSampleID.Text = reader["SampleID"].ToString();
txtUpdateSampleType.Text = reader["SampleType"].ToString();
txtUpdateSampleDate.Text = reader["SampleDate"].ToString();
txtUpdateSampleTrial.Text = reader["SampleTrial"].ToString();
DropDownListUpdateFirstSample.SelectedItem.Value = reader["FirstSample"].ToString();
txtUpdateSampleComments.Text = reader["Comments"].ToString();
txtUpdateSampleConsultant.Text = reader["ConsultantName"].ToString();
DropDownListUpdate.SelectedItem.Value = reader["Diagnosis"].ToString();
DropDownListUpdateConsentConfirm.SelectedItem.Value = reader["ConsentConfirmed"].ToString();
txtUpdateConsentDate.Text = reader["DateConsent"].ToString();
txtUpdateOrther.Text = reader["OtherConsent"].ToString();
DropDownListUpdateSectionDecline.SelectedItem.Value = reader["SectionDecline"].ToString();
DropDownListUpdateQuarantine.SelectedItem.Value = reader["Quarantine"].ToString();
DropDownListUpdateClinicalArchive.SelectedItem.Value = reader["ClinicalArchive"].ToString();
DropDownListUpdateResearch.SelectedItem.Value = reader["Research"].ToString();
//DropDownListUpdateClinicalArchive.SelectedItem.Value= reader["Research"].ToString();
}
}
}
con.Close();
}
}
Use the below code:
public void functionForSelectedValue(int id)
{
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
{
con.Open();
using (SqlCommand st = new SqlCommand(#"SELECT *
FROM Sample
WHERE
SampleID=#SampleID", con))
{
st.Parameters.AddWithValue("#SampleID", id);
using (SqlDataReader reader = st.ExecuteReader())
{
while (reader.Read())
{
txtUpdateSampleID.Text = reader["SampleID"].ToString();
txtUpdateSampleType.Text = reader["SampleType"].ToString();
txtUpdateSampleDate.Text = reader["SampleDate"].ToString();
txtUpdateSampleTrial.Text = reader["SampleTrial"].ToString();
DropDownListUpdateFirstSample.SelectedItem.Value = reader["FirstSample"].ToString();
txtUpdateSampleComments.Text = reader["Comments"].ToString();
txtUpdateSampleConsultant.Text = reader["ConsultantName"].ToString();
DropDownListUpdate.SelectedItem.Value = reader["Diagnosis"].ToString();
DropDownListUpdateConsentConfirm.SelectedItem.Value = reader["ConsentConfirmed"].ToString();
txtUpdateConsentDate.Text = reader["DateConsent"].ToString();
txtUpdateOrther.Text = reader["OtherConsent"].ToString();
DropDownListUpdateSectionDecline.SelectedItem.Value = reader["SectionDecline"].ToString();
DropDownListUpdateQuarantine.SelectedItem.Value = reader["Quarantine"].ToString();
DropDownListUpdateClinicalArchive.SelectedItem.Value = reader["ClinicalArchive"].ToString();
DropDownListUpdateResearch.SelectedItem.Value = reader["Research"].ToString();
//DropDownListUpdateClinicalArchive.SelectedItem.Value= reader["Research"].ToString();
}
}
}
con.Close();
}
}
protected void DropDownListUpdateSample_SelectedIndexChanged(object sender, EventArgs e)
{
functionForSelectedValue(DropDownListUpdateSample.SelectedItem.Value);
}
And in page load:
call
foreach (DataRow tempRow_Variable in myDataTable.Rows)
{
var tempRow = tempRow_Variable;
DropDownListUpdateSample.Items.Add(tempRow["SampleID"].ToString());
}
DropDownListUpdateSample.Items.FindByValue("IdforWhichYouWantTobindIt").Selected = true;
functionForSelectedValue(DropDownListUpdateSample.SelectedItem.Value);
Hope this solves your problem.

get all row and column data using SELECT - C#

I'm trying to get all data from an SQL table and store it in a List using the C# programming language.
the SQL statement I'm using is:
private string cmdShowEmployees = "SELECT * FROM Employees;";
This is being used in the same class as a function
public List<string> showAllIdData()
{
List<string> id = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
id.Add(reader[0].ToString());
}
return id;
}
}
and here
public List<string> showAllActiveData()
{
List<string> active = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
active.Add(reader[1].ToString());
}
return active;
}
I would have to create 9 more functions this way in order to get all the data out of the Employees table. This seems very inefficient and I was wondering if there was a more elegant way to do this.
I know using an adapter is one way to do it but I don't think it is possible to convert a filled adapter to a list, list list etc.
SqlDataAdapter adapter = sqlDataCollection.getAdapter();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "idEmployees");
dataGridView1.DataSource = dataset;
dataGridView1.DataMember = "idEmployees";
Any ideas?
If you must use the reader in this way, why not create an object which holds the table row data.
public class SomeComplexItem
{
public string SomeColumnValue { get; set;}
public string SomeColumnValue2 { get; set;}
public string SomeColumnValue3 { get; set;}
public string SomeColumnValue4 { get; set;}
}
That way you can loop through with your reader as follows:
public List<SomeComplexItem> showAllActiveData()
{
List<SomeComplexItem> active = new List<SomeComplexItem>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
var someComplexItem = new SomeComplexItem();
someComplexItem.SomeColumnValue = reader[1].ToString();
someComplexItem.SomeColumnValue2 = reader[2].ToString();
someComplexItem.SomeColumnValue3 = reader[3].ToString();
active.Add(someComplexItem);
}
return active;
}
You could use two select statements to populate two List<string> as shown in the example below where the key between reads is reader.NextResult();.
The database used is the standard Microsoft NorthWind database.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace SQL_Server_TwoList
{
public class DataOperations
{
public List<string> Titles { get; set; }
public List<string> Names { get; set; }
/// <summary>
/// Trigger code to load two list above
/// </summary>
public DataOperations()
{
Titles = new List<string>();
Names = new List<string>();
}
public bool LoadData()
{
try
{
using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
string commandText = #"
SELECT [TitleOfCourtesy] + ' ' + [LastName] + ' ' + [FirstName] As FullName FROM [NORTHWND.MDF].[dbo].[Employees];
SELECT DISTINCT [Title] FROM [NORTHWND.MDF].[dbo].[Employees];";
using (SqlCommand cmd = new SqlCommand(commandText, cn))
{
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Names.Add(reader.GetString(0));
}
// move on to second select
reader.NextResult();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Titles.Add(reader.GetString(0));
}
}
}
}
}
return true;
}
catch (Exception)
{
return false;
}
}
}
}
Form code
namespace SQL_Server_TwoList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataOperations dataOps = new DataOperations();
if (dataOps.LoadData())
{
listBox1.DataSource = dataOps.Names;
listBox2.DataSource = dataOps.Titles;
}
}
}
}
You could always add it all to a dataset or datatable instead of looping through using datareader to add to an array, dataset allows you to access data in similar way to array anyway.
Connstr = "Data Source = " + SelectedIP + "; Initial Catalog = " + dbName + "; User ID = " + txtUsername.Text +"; Password = "+ txtPassword.Text +"";
conn = new SqlConnection(Connstr);
try
{
string contents = "SELECT * FROM ..."
conn.Open();
SqlDataAdapter da_1 = new SqlDataAdapter(contents, conn); //create command using contents of sql file
da_1.SelectCommand.CommandTimeout = 120; //set timeout in seconds
DataSet ds_1 = new DataSet(); //create dataset to hold any errors that are rturned from the database
try
{
//manipulate database
da_1.Fill(ds_1);
if (ds_1.Tables[0].Rows.Count > 0) //loop through all rows of dataset
{
for (int i = 0; i < ds_1.Tables[0].Rows.Count; i++)
{
//rows[rownumber][column number/ "columnName"]
Console.Write(ds_1.Tables[0].Rows[i][0].ToString() + " ");
}
}
}
catch(Exception err)
{}
conn.Close();
}
catch(Exception ex)
{}

How to select multiple items using Autocomplete extender in c#?

In my project I am using autocomplete extender.using this I am selecting only one item.But I want to select multiple items.what I should I do.please help me. below is my code:
aspx page:
<asp:TextBox ID="TextBox1" runat="server" CssClass="autosuggest ui-timepicker-input" Width="300px"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" DelimiterCharacters=""
Enabled="True" ServiceMethod="GetListofCountries" MinimumPrefixLength="2" EnableCaching="true" CompletionSetCount="10" CompletionInterval="10" FirstRowSelected="false"
TargetControlID="TextBox1">
</ajaxToolkit:AutoCompleteExtender>
aspx.cs page:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetListofCountries(string prefixText, int count)
{
//using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["con2"].ConnectionString))
//{
// sqlconn.Open();
// SqlCommand cmd = new SqlCommand("select UserEmail from [User] where Useremail like '%" + prefixText + "%'", sqlconn);
// cmd.Parameters.AddWithValue("#prefixText", prefixText);
// SqlDataAdapter da = new SqlDataAdapter(cmd);
// DataTable dt = new DataTable();
// da.Fill(dt);
// List<string> Emailid = new List<string>();
// for (int i = 0; i < dt.Rows.Count; i++)
// {
// Emailid.Add(dt.Rows[i]["UserEmail"].ToString());
// }
// return Emailid;
//}
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
List<string> terms = prefixText.Split(',').ToList();
terms = terms.Select(s => s.Trim()).ToList();
//Extract the term to be searched from the list
string searchTerm = terms.LastOrDefault().ToString().Trim();
//Return if Search Term is empty
if (string.IsNullOrEmpty(searchTerm))
{
// return
}
//Populate the terms that need to be filtered out
List<string> excludeTerms = new List<string>();
if (terms.Count > 1)
{
terms.RemoveAt(terms.Count - 1);
excludeTerms = terms;
}
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["con2"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
string query = "select UserEmail from [User] where Useremail like '%" + prefixText + "%'";
//Filter out the existing searched items
if (excludeTerms.Count > 0)
{
query += string.Format(" and UserEmail not in ({0})", string.Join(",", excludeTerms.Select(s => "'" + s + "'").ToArray()));
}
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#prefixText", prefixText);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
//customers.Add(string.Format("{0}-{1}", sdr["Userid"], sdr["CustomerId"]));
customers.Add(string.Format("{0}", sdr["UserEmail"]));
}
}
conn.Close();
}
return customers;
}
but it gives only one value.I want to select multiple items.please help me.
finally I got an answer for the above question.in the AutoCompleteExtender add DelimiterCharacters="," and ShowOnlyCurrentWordInCompletionListItem="true" . add this two items for the AutoCompleteExtender. It will work for me.if any one want this type of question, I hope this answer is help you,thats why I posted here.thank you.

Categories

Resources