C# adding every table row to textbox from database - c#

I've been working a bit with binding database tables to text boxes and I've encountered a problem. The code I have here gets all the columns I need from the table, but only 1 row's worth of data shows up. Is there a simple way to make every single row from the table appear in a text box? Or some other sort of text list?
SqlConnection cn = new SqlConnection("SERVER=myserver;DATABASE=mydb;Trusted_Connection=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr = null;
cmd.Connection = cn;
cn.Open();
cmd.CommandText = "SELECT DisasterID,DisasterType,Location,CurrentStatus,IntensityLevel,Latitude,Longitude FROM Disasters";
dr = cmd.ExecuteReader();
if (dr.Read()) {
txtFeeds.Text = dr["DisasterID"].ToString() + " " + dr["DisasterType"].ToString() + " " + dr["Location"].ToString() + " " + dr["CurrentStatus"].ToString() + " " + dr["IntensityLevel"].ToString() + " " + dr["Latitude"].ToString() + " " + dr["Longitude"].ToString();
}
cn.Close();

You need while loop and append each line to textbox by txtFeeds.Text +=
while(dr.Read()) {
txtFeeds.Text += dr["DisasterID"].ToString() + " "
+ dr["DisasterType"].ToString() + " "
+ dr["Location"].ToString() + " "
+ dr["CurrentStatus"].ToString() + " "
+ dr["IntensityLevel"].ToString() + " "
+ dr["Latitude"].ToString() + " " + dr["Longitude"].ToString();
}
If you need more performance you can use StringBuilder to append text and finally set textbox text using StringBuilder.ToString method.
Edit.
StringBuilder sb = new StringBuilder();
while (dr.Read())
{
sb.AppendLine(dr["DisasterID"].ToString() + " "
+ dr["DisasterType"].ToString() + " "
+ dr["Location"].ToString() + " "
+ dr["CurrentStatus"].ToString() + " "
+ dr["IntensityLevel"].ToString() + " "
+ dr["Latitude"].ToString() + " " + dr["Longitude"].ToString());
}
txtFeeds.Text = sb.ToString();

First of all its a bad idea trying display records from a table in a single textbox.
If you still want to do it,
Use a while loop instead of IF condition
while(dr.Read())
{
}
Use a string builder and append all your column values to it and after while loop exists use the values in the string builder and set it to the field.
StringBuilder values = new StringBuilder();
while(dr.Read()) {
values.Append( dr["DisasterID"].ToString() + " " + dr["DisasterType"].ToString() + " " + dr["Location"].ToString() + " " + dr["CurrentStatus"].ToString() + " " + dr["IntensityLevel"].ToString() + " " + dr["Latitude"].ToString() + " " + dr["Longitude"].ToString());
}
txtFeeds.Text = values.ToString();

Related

Error ORA-00907 Right parenthesis missing

Hello i have a long SQL Query for Oracle DB. My Problem is i'm searching for arround 2 hours to get the error fixed. On all Queries i have the same error with parenthesis.
Here is my class where i get the error inside the command of OracleDB Query. I didnt find the error. The Query shown below is working on Delphi without problems. The only thing i change are the quotation marks at the beginning and at the end of each line which a normally single quoted.
using System;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;
namespace RawBinderLabel
{
public partial class Rawbinder_Manually : Form
{
private database_conn db_conn = new database_conn();
private OracleConnection OraConn = new OracleConnection();
public Rawbinder_Manually()
{
InitializeComponent();
get_rawbinder_data();
}
public void get_rawbinder_data()
{
string rcs = db_conn.connection();
using (OracleConnection OraConn = new OracleConnection(rcs))
{
using (OracleCommand OraCmd = OraConn.CreateCommand())
{
try
{
OraConn.Open();
OraCmd.BindByName = true;
//SQL Command to retrieve manual binder that ar OK
OraCmd.CommandText = "SELECT l.a_layer_pos, " +
" l.a_serial, " +
" P_ROHBINDER_ETIKETTEN.GET_BARCODE (mb.a_serial,''M'') Barcode, " +
" mb.a_splitted," +
" mb.a_dlam, " +
" l.a_order_id, " +
" l.a_section_id, " +
" P_ROHBINDER_ETIKETTEN.GET_MANUALPOSITIONS (mb.a_serial) Positionen, " +
" P_ROHBINDER_ETIKETTEN.GET_MANUALABBUND (mb.a_serial) abbund, " +
" P_ROHBINDER_ETIKETTEN.GET_MANUALQUALITY (mb.a_prodquality_id) qualitaet, " +
" to_char(lt.LIEFERTERMIN, ''dd.mm.yyyy'') liefertermin, " +
" ''1'' a_beam_pos, " +
" P_ROHBINDER_ETIKETTEN.GET_MAXMANUALLENGTH (l.a_serial) max_a_length, " +
" substr(c.a_cust_name,1,40) kunde, " +
" l.a_dimter_start_date, " +
" l.a_dimter_end_date, " +
" p.a_prod_date, " +
" p.a_destheight, " +
" p.a_description, " +
" dl.a_layer_serial, " +
" dl.a_width, " +
" dl.a_lamellaheight, " +
" dl.A_RAWWIDTH, " +
" dl.A_RAWLAMELLAHEIGHT, " +
" dl.A_GLUE_DESCRIPTION, " +
" dl.A_COLOR_DESCRIPTION, " +
" dl.a_pressproc_description, " +
" dl.a_pressproc_description ||' - ' || p.a_description || '' - ('' ||p.a_destlength || '')'' pressbett, " +
" mb.a_serial beam_serial," +
" mb.a_prodquality_id," +
" FROM t_manual_layer l," +
"t_manual_pressproc p, " +
"t_dimter_layer dl, " +
"t_manualbeam mb, " +
"v_liefertermin lt, " +
"t_order o, " +
"t_customer c " +
" WHERE to_char(p.a_prod_date,''DD.MM.YYYY'') = ''' :rawbinder_date '''" +
" and p.a_pressproc_id = l.a_pressproc_id " +
" AND l.A_SERIAL = dl.A_SERIAL " +
" AND mb.A_LAYER_SERIAL = l.a_serial " +
" AND lt.PROJEKTNR = l.a_order_id " +
" AND lt.GPID = l.a_section_id " +
" AND o.a_order_id = l.a_order_id " +
" and c.a_customer_id = o.a_customer_id " +
" order by l.A_SERIAL, l.a_layer_pos";
//Assign Parameters to Date selected in Overview Form
OracleParameter rawbinder_date = new OracleParameter("rawbinder_date", RawBinder_Overview.rawbinder_date);
OraCmd.Parameters.Add(rawbinder_date);
//Execute the command and display it using DataReader
OracleDataReader OraDataRead = OraCmd.ExecuteReader();
while (OraDataRead.Read())
{
Console.WriteLine("Manually Implemented" + OraDataRead.GetString(0));
}
}
catch (OracleException ex)
{
switch (ex.Number)
{
case 1:
MessageBox.Show("Fehler beim Einfügen der Daten");
break;
case 12560:
MessageBox.Show("Die Datenbank ist nicht erreichbar.");
break;
default:
MessageBox.Show("Datenbankfehler: " + ex.Message.ToString());
break;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
OraConn.Dispose();
}
}
}
}
}
}
Does someone has an Idea how to fix that Problem?
I think there are multiple issues:
2 times single quotes are not required everywhere
comma after " mb.a_prodquality_id," + is not required as it is the last expression of SELECT clause
as mentioned in the comment by #crowcoder, single quotes around parameters are not required. Means around this: :rawbinder_date
Try to solve all this problems and check if it executes properly.

CSVHelper - ignore blank cells in a row unless they are populated

Using CsvHelper with .NET Core 2.2.
We're parsing a CSV file to then export to a SQL table. There are two different mappings of the CSV columns to the SQL columns, which depend on the first value of each row of the CSV.
This is what we have:
public List<TaskProdEntity> ParseCSVFile()
{
using (var reader = new StreamReader(#"C:\Users\me\Desktop\pfile.csv"))
using (var csv = new CsvReader(reader))
{
csv.Configuration.PrepareHeaderForMatch = (string header, int index) =>
header.Replace(" ", "_").Replace("(", "").Replace(")", "").Replace(".", "");
List<TaskProdEntity> records = new List<TaskProdEntity>();
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
if (csv.GetField<int>(0) == 1)
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id"),
Region = "Business Mailing Address:" + " " + csv.GetField<string>("Provider_First_Line_Business_Mailing_Address") + " " + csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_City_Name") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_State_Name") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Postal_Code") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Country_Code_If_outside_US") + " | " + "Business Practice Location:" + " " + csv.GetField<string>("Provider_First_Line_Business_Practice_Location_Address") + " " + csv.GetField<string>("Provider_Second_Line_Business_Practice_Location_Address") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_City_Name") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_State_Name") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Postal_Code") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Country_Code_If_outside_US"),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_1")
};
records.Add(record);
}
else
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id3"),
Region = "Business Mailing Address:" + " " + csv.GetField<string>("Provider_First_Line_Business_Mailing_Address2") + " " + csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_City_Name2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_State_Name2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Postal_Code2") + " " + csv.GetField<string>("Provider_Business_Mailing_Address_Country_Code_If_outside_US2") + " | " + "Business Practice Location:" + " " + csv.GetField<string>("Provider_First_Line_Business_Practice_Location_Address2") + " " + csv.GetField<string>("Provider_Second_Line_Business_Practice_Location_Address2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_City_Name2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_State_Name2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Postal_Code2") + " " + csv.GetField<string>("Provider_Business_Practice_Location_Address_Country_Code_If_outside_US2"),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_2")
};
records.Add(record);
}
}
return records;
}
}
Because the mapping for the Region field specifically is so messy and long, I really want to extract values from those csv fields only if the field is not blank. In many cases, many of those fields will be blank, and the business does not want a ton of concatenated blanks to end up in the database in these cases.
I am wondering if CsvHelper already has a built-in function to achieve this? If not, how would I implement that logic into the above code?
Since the second TaskProdEntity appears to add a 2 each time to the column header, you could have one method that builds your address.
public List<TaskProdEntity> ParseCSVFile()
{
using (var reader = new StreamReader(#"C:\Users\me\Desktop\pfile.csv"))
using (var csv = new CsvReader(reader))
{
csv.Configuration.PrepareHeaderForMatch = (string header, int index) =>
header.Replace(" ", "_").Replace("(", "").Replace(")", "").Replace(".", "");
List<TaskProdEntity> records = new List<TaskProdEntity>();
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
if (csv.GetField<int>(0) == 1)
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id"),
Region = GetAddress(csv),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_1")
};
records.Add(record);
}
else
{
var record = new TaskProdEntity
{
Identifier = "ID Number:" + " " + csv.GetField<string>("Id3"),
Region = GetAddress(csv, "2"),
Program = "Taxonomy Group:" + " " + csv.GetField<string>("Taxonomy_Group_2")
};
records.Add(record);
}
}
return records;
}
}
private string GetAddress(CsvReader csv, string extension = "")
{
var value = new StringBuilder("Business Mailing Address:");
if (csv.GetField<string>("Provider_First_Line_Business_Mailing_Address" + extension) != string.Empty)
{
value.Append(" " + csv.GetField<string>("Provider_First_Line_Business_Mailing_Address" + extension));
}
if (csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address" + extension) != string.Empty)
{
value.Append(" " + csv.GetField<string>("Provider_Second_Line_Business_Mailing_Address" + extension));
}
// The rest of the if statements..............
return value.ToString();
}

HttpClient put issue in Angular

I'm developing an Angular app with Web api.
I have created a service (sellerService) in which I can update some data in my database with HttpClient put.
Above works but it update all the data of my table, something like follows;
Before I update my seller:
After I update my seller:
My sellerService code:
updateSeller(user: string, nbsales: number, pVote: number, nVote: number, idUser: number): Observable<any> {
return this.http.put('http://localhost:50867/api/seller_user/', {
'username': user,
'nbSales': nbsales,
'positiveVote': pVote,
'negativeVote': nVote,
'idUser': idUser
});
}
My update query (DAO (c#)):
public static readonly string UPDATE = "update " + TABLE_NAME + " set "
+ COLUMN_USERNAME + " =#username"
+ ", " + COLUMN_NB_SALES + "=#nbSales"
+ ", " + COLUMN_POSITIVE_VOTE + "=#positiveVote"
+ ", " + COLUMN_NEGATIVE_VOTE + " =#negativeVote"
+ ", " + COLUMN_ID_USER + "=#idUser";
//Update a seller_user
public static bool Update(Seller_user todo)
{
bool state = false;
using (SqlConnection connection = DataBase.GetConnection())
{
connection.Open();
SqlCommand command = new SqlCommand(UPDATE, connection);
//command.Parameters.AddWithValue("#idSeller", todo.idSeller);
command.Parameters.AddWithValue("#username", todo.username);
command.Parameters.AddWithValue("#nbSales", todo.nbSales);
command.Parameters.AddWithValue("#positiveVote", todo.positiveVote);
command.Parameters.AddWithValue("#negativeVote", todo.negativeVote);
command.Parameters.AddWithValue("#idUser", todo.idUser);
state = command.ExecuteNonQuery() != 0;
}
return state;
}
Thanks in advance ;)
You missed where clause in SQL query. So it will update all records.
public static readonly string UPDATE = "update " + TABLE_NAME + " set "
+ COLUMN_USERNAME + " =#username"
+ ", " + COLUMN_NB_SALES + "=#nbSales"
+ ", " + COLUMN_POSITIVE_VOTE + "=#positiveVote"
+ ", " + COLUMN_NEGATIVE_VOTE + " =#negativeVote"
+ ", " + COLUMN_ID_USER + "=#idUser"
+ "WHERE " + COLUMN_ID_USER + "=" + "= #idUser";

How to populate treenode from SQL using C#

I inherited a project that is populating TreeNode from SQL. I want to add three columns but syntax checker doesn't like what I'm adding but appears consistent with examples in blogs.
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString()); // current working code
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString() + " - " + rdr["FieldType"].ToString() + " - " + rdr["PointsToFileNumber"].ToString() + " - " + rdr["FieldLength"].ToString()); //possible replacement code that works but I would have to parse it later
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString(), rdr["FieldType"].ToString(), rdr["PointsToFileNumber"].ToString(), rdr["FieldLength"].ToString()); //bad syntax beginning at first comma
Method:
private void getFileManFields(TreeNode node)
{
node.Nodes.Clear();
String fileNumber = node.Tag.ToString();
String sta3n = cbRegionSites.SelectedItem.ToString().Substring(1, 3);
SqlConnection cdw = new SqlConnection(ConfigurationManager.ConnectionStrings["CDW"].ConnectionString);
cdw.Open();
//SqlCommand cmd = new SqlCommand("SELECT VistaFieldNumber,VistaFieldName,MultipleFileNumber FROM CDWWork.Dim.VistaField WHERE Sta3n=" + sta3n + " AND VistaFileNumber='" + fileNumber + "' ORDER BY CAST(VistaFieldNumber As NUMERIC(30,10))", cdw);
SqlCommand cmd = new SqlCommand("SELECT VistaFieldNumber,VistaFieldName,MultipleFileNumber,FieldType,PointsToFileNumber,FieldLength FROM CDWWork.Dim.VistaField WHERE Sta3n=" + sta3n + " AND VistaFileNumber='" + fileNumber + "' ORDER BY CAST(VistaFieldNumber As NUMERIC(30,10))", cdw);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString());
//TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString() + " - " + rdr["FieldType"].ToString() + " - " + rdr["PointsToFileNumber"].ToString() + " - " + rdr["FieldLength"].ToString());
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString(), rdr["FieldType"].ToString(), rdr["PointsToFileNumber"].ToString(), rdr["FieldLength"].ToString());
field.Tag = rdr["VistaFieldNumber"].ToString();
if (rdr["MultipleFileNumber"].ToString().Length > 0)
{
field.Tag = rdr["MultipleFileNumber"].ToString();
field.Nodes.Add("RemoveNode");
}
node.Nodes.Add(field);
}
rdr.Close();
rdr.Dispose();
cmd.Dispose();
cdw.Close();
cdw.Dispose();
}

header and footer in text file using c#

I am newbie to c# I want to have headers and footers when saving the text file which is generated on the data grid view.
when I run a sql query it should generate 3 column values as headers and 3 columns values as footers.
headers recordtype,cpcnumber,filesequence number;
footers record type,no of requests,total court fee,claim amount; I don't how to get these records when i run this command as headers/footers. Any help would be greatly appreciated..
private void btnGetData_Click(object sender, EventArgs e)
{
this.btnGetData.Enabled = false;
Application.DoEvents();
string stringSql = " SELECT distinct " +
"'" + comboBox6.Text + "' as RecordType" +
" , left([CPC No] +' ',30) " +
" , space(1983) " +
",'" + comboBox6.Text + " 'as RecordType" +
, left(t.t_reference + ' ' ,24 ) as ClaimantReference " +
" , left([Claim Number] +' ',30) " +
" , " + comboBox4.Text + " as CourtCode" +
" ,left(ta_title +' ',30) as Title " +
" ,left(ta_surname +' ',30) as Surname " +
", space(180), bat.PCN_Charge as ClaimAmount " +
",[Court Fee] " +
",[Solictors Fees]" +
", (bat.PCN_Charge + [Court Fee]) as TotalAmount" +
",[POC1]" +
",'" + textBox2.Text + "' as RequestType" +
//",'" + comboBox1.Text + "' as RecordType" +
",'" + textBox3.Text + "' as TotalCourtFee" +
",'" + textBox4.Text + "' as TotalClaimAmount" +
" , space(1966) " +
" FROM tickets t " +
" LEFT OUTER JOIN " +
"( " +
" SELECT ticket_addresses.ta_system_ref, ta_title, ta_othername, ta_surname, ta_house_number, ta_address_1, ta_address_2, " +
" ta_address_3, ta_address_4, ta_post_code, ta_telephone, ta_organisation " +
" FROM ticket_addresses " +
" INNER JOIN " +
" ( " +
" SELECT ticket_addresses.ta_system_ref, MAX(ta_address_code) AS ta_address_code " +
" FROM ticket_addresses " +
" GROUP BY ta_system_ref " +
" ) ad " +
" ON (ticket_addresses.ta_system_ref=ad.ta_system_ref AND ticket_addresses.ta_address_code=ad.ta_address_code) " +
")ta " +
"ON (t.t_number=ta.ta_system_ref) " +
" " +
" Inner JOIN " +
" ticket_hold_record b " +
" ON ( t.t_number = b.thr_system_ref) " +
" " +
"Inner JOIN " +
"Rpt_PCNBalance_ALLTickets bat " +
"ON (t.t_number = bat.t_number) " +
" " +
"Inner JOIN " +
"hold_reasons ch " +
"ON (b.thr_hold_type = ch.hr_code) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[Courtfees] cf " +
" ON (bat.Payments >= cf. [Min ClaimAmount]) and (bat.Payments <= cf.[Max Claim Amount]) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[sites] s " +
" ON (t.t_contract = s.Contract) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[claim info] cc " +
" ON (cc.Code COLLATE DATABASE_DEFAULT = t.t_offence_code COLLATE DATABASE_DEFAULT) " +
" and t.t_reference IN {where} ";
//Generate list of Ticket IDS for SQL Where Clause
string whereClause = "";
string[] tempArray = new string[this.txt.Lines.Length];
tempArray = this.txt.Lines;
if (this.txt.Lines.Length == 0)
{
return;
}
for (int counter = 0; counter <= tempArray.Length-1; counter++)
{
if (tempArray[counter].Trim().Length > 0)
{
whereClause = whereClause + "'" + tempArray[counter] + "'" + ", ";
}
}
whereClause = whereClause.TrimEnd(' ', ',');
whereClause = "(" + whereClause + ")";
stringSql = stringSql.Replace("{where}", whereClause);
myDataset = new DataSet("SQL");
SqlConnection myConn = new SqlConnection();
SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.Text;
myCommand.CommandText = stringSql;
myCommand.Connection = myConn;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(myDataset);
this.dataGridView1.DataSource = myDataset.Tables[0];
for (int counter = 0; counter < myDataset.Tables[0].Columns.Count; counter++)
{
this.dataGridView1.Columns[counter].SortMode = DataGridViewColumnSortMode.NotSortable;
}
this.dataGridView1.Refresh();
myConn.Close(); this.btnGetData.Enabled = true;
this.btnSave.Enabled = true;
Application.DoEvents();
}

Categories