compare the length of two variable - c#

I am a beginner programmer.
I wrote following code and I want to compare the lenght of the Track ID (which is in my data set) with the Track ID (which is extracted from the web page) which both are highlighted.(my data set has two fields(user id-track id), i want to compare this track id with the track id which is return from web page)
I want to to it like:
if (client.Contains(Convert.ToString(TrackID))&&row["TrackID"].lenght=Track ID.lenght)
Thank you
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\hidden.accdb";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from hidden.accdb";
DataTable dt = new DataTable();
//To read data from dataset
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
//Store the UserID
adapter.Fill(dt);
int UserID=0,TrackID=0;
int counter=0;
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");
if (client.ToLower() == (Convert.ToString(TrackID).ToLower()))
{
counter++;
}
int ave = counter / 2916;
MessageBox.Show("Average" + counter);
}
conn.Close();
}
}
}

Why not do this?
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");
if (client.ToLower() == Convert.ToString(TrackID).ToLower())
{
counter++;
}

Related

Fill and append data dynamically from mutiple OledbConnections to one single OleDbDataAdapter

I'm trying to dynamically add rows from some excel files located in a directory to a OleDbDataAdapter.
So far,I managed to add some data to the OleDbDataAdapter by dynamically generating OleDbConnections that each point to the respective excel files from which i want to read data. However, the code stops after reading the first excel file. I suspect that I have to clear some variables but I'm kinda stuck for now.
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApp35
{
class Program
{
static void Main(string[] args)
{
string dirALC_EDC = #"C:\Users\________\Desktop\Mission\Fichiers\ALC_EDC\";
var files = Directory.GetFiles(dirALC_EDC, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
String theConnString = (String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", file));
OleDbConnection excelConnection = new OleDbConnection(theConnString);
excelConnection.Open();
var dt = new DataTable();
var da = new OleDbDataAdapter();
var _command = new OleDbCommand();
_command.Connection = excelConnection;
_command.CommandText = "select * FROM [Sheet1$]";
da.SelectCommand = _command;
try
{
da.Fill(dt);
for (int i = 4; i <= dt.Rows.Count; i++)
{
Console.WriteLine(String.Join(", ", dt.Rows[i].ItemArray));
}
}
catch (Exception e)
{
// process error here
}
Console.ReadLine();
}
}
}
}

How to use DataTable from SQL Server in C#

I want to view this table in the list box in C#
enter image description here
I'm using this query to show the table
select
Chicken_Name, WithOrWithout_Name, Chicken_Price
from
Tbl_Add a
full outer join
tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID
full outer join
Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ;
And this code to put it in the list box in C#
private void Chicken()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Chicken_Name,WithOrWithout_Name,Chicken_Price from Tbl_Add a full outer join tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Chicken = new DataTable();
adapter.Fill(tbl_Chicken);
lst_SHowdata.DisplayMember = "Chicken_Name";
lst_SHowdata.ValueMember = "Chicken_ID";
lstSHowdata2.DisplayMember = "Chicken_Price";
lst_SHowdata.DataSource = tbl_Chicken;
lstSHowdata2.DataSource = tbl_Chicken;
This is the full code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace HABIBIS_GRILL
{
public partial class HabibisGrll : Form
{
SqlConnection connection;
string connectionString;
public HabibisGrll()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["HABIBIS_GRILL.Properties.Settings.HabibisGrilllDataBAseConnectionString"].ConnectionString;
}
private void Form1_Load(object sender, EventArgs e)
{
Chicken();
}
private void Chicken()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Chicken_Name,WithOrWithout_Name,Chicken_Price from Tbl_Add a full outer join tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Chicken = new DataTable();
adapter.Fill(tbl_Chicken);
lst_SHowdata.DisplayMember = "Chicken_Name";
lst_SHowdata.ValueMember = "Chicken_ID";
lstSHowdata2.DisplayMember = "Chicken_Price";
lst_SHowdata.DataSource = tbl_Chicken;
lstSHowdata2.DataSource = tbl_Chicken;
}
}
}
}
The problem is I need to use one list box for each column, how to make them in one list box or do I use another tool ?
And how to put 2 or more tables in one datatable (adapter) ?
Thank you ^^"
first question:
you can use gridview for your query if you want to show more than 1 column from your query.
Second question:
and you can use DataSet to get more than 1 table in case you need.
check this:
string queryCustomer =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryCustomer , connection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet , "Customers");
string queryOrders =
"SELECT OrderId, Date FROM dbo.Orders";
SqlDataAdapter adapterOrder = new SqlDataAdapter(queryOrders , connection);
adapterOrder.Fill(dataSet , "Orders");
//assume you have a GridView named myGridview.
//than set its DataSource to one of your DataSet tables.
myGridview.DataSource = dataSet.Tables[0] //customers will be the source

c# : How to get data from database and pass to another form?

I'm building a desktop application where when a used logged it in new his Id will be appeared in textBox. But in my case query run successfully but id doesn't appear in textBox..can anyone help me to find it out please?
First form of User logged in (Form1.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class login : Form
{
public login()
{
InitializeComponent();
}
public string employeeID;
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void loginButton_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True");
connection.Open();
String query = "select * from Employees where Name = '" + nameTextBox.Text + " ' and Password = '" + passwordTextBox.Text + "'";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
string employeeID = myReader["EmployeeID"].ToString();
}
myReader.Close();
SqlDataAdapter sda = new SqlDataAdapter(query,connection);
connection.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
}
}
}
Second form (Entry.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class Entry : Form
{
public Entry()
{
InitializeComponent();
}
public Entry(string employeeId)
{
InitializeComponent();
idTextBox.Text = employeeId;
}
private void reportButton_Click(object sender, EventArgs e)
{
Report report = new Report();
report.Show();
}
}
}
Remove local variable declaration, because employeeID is a global variable and already declared first, so when you prefix it using string its create another local variable which is not accessible outside this scope
while (myReader.Read())
{
employeeID = myReader["EmployeeID"].ToString();
}
You have a local variable. You can correct and optimize you code like this:
private void loginButton_Click(object sender, EventArgs e)
{
//If use set quote into your textbox
string name = nameTextBox.Text.Replace("'", "''");
string pass = passwordTextBox.Text.Replace("'", "''");
String query = string.Format("select * from Employees where Name = '{0}' and Password = '{1}'", name, pass);
string employeeID = "";
using (SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True"))
{
connection.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(query, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
employeeID = dt.Rows[0]["EmployeeID"].ToString();
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
dt.Dispose();
}
}
}

Storing Selected CheckedListBox Values in Database

I have two tables in my database. Let's say table A and table B. table A values are put in checkedlistbox. The selected values in checkedlistbox then are put into table B. I tried to make a code however it wont work. Do you have any idea on how to make this problem work?
thanks ahead guys.
by the way im using c#.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Npgsql;
namespace WindowsFormsApplication1
{
public partial class Form8 : Form
{
public Form8()
{
InitializeComponent();
this.Load += Form8_Load;
button2.Click += button2_Click;
}
private void Form8_Load(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("SELECT conname FROM condition", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
using (NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
((ListBox)checkedListBox1).DataSource = dt;
((ListBox)checkedListBox1).DisplayMember = "conname";
((ListBox)checkedListBox1).DisplayMember = "conid";
string[] condition = dt.Rows[0]["conname"].ToString().Split(',');
}
}
private void button2_Click(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
conn.Open();
cmd.Parameters.AddWithValue("#famid", checkedListBox1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data has been saved");
conn.Close();
}
}
}
You have to iterate through all the selected items:
//check if any item is selected
if (checkedListBox1.SelectedItems.Count > 0)
{
//connect to database
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
//loop through all selected items
foreach (object item in checkedListBox1.CheckedItems)
{
//convert item to string
string checkedItem = item.ToString();
//insert item to database
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
cmd.Parameters.AddWithValue("#famid", checkedItem); //add item
cmd.ExecuteNonQuery();
}
//close connection
conn.Close();
MessageBox.Show("Data has been saved");
}
Note: I am executing all insert commands in one open connection, because opening and closing connection frequently is not best practice.

Error in adapter.fill function

I am a beginner programmer.
I wrote the following code that shows an error in "adapter.fill(dt) ??????
this code must do the following steps:
1-connect to my dataset that has two fields :UserID,TrackID (2916 fields) 2-Read the dataset line by line and put the UserId of each recored to a url(instead of ). 3-Search through the webpage 4-if it finds the TrackId (exactly the same) which is related to UserId, add 1 to counter.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\hidden.accdb";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from hidden.accdb";
DataTable dt = new DataTable();
//To read data from dataset
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
//Store the UserID
adapter.Fill(dt);
int UserID=0,TrackID=0;
int counter=0;
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");
if (client.ToLower() == (Convert.ToString(TrackID).ToLower()))
{
counter++;
}
int ave = counter / 2916;
MessageBox.Show("Average" + counter);
}
conn.Close();
}
}
}
This is invalid:
"Select * from hidden.accdb"
hidden.accdb should be table name that contains the UserID and TrackID columns. not access database file name

Categories