How to use DataTable from SQL Server in C# - 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

Related

Chart COUNT Query C#?

Kinda new to C#, I'm a bit confused with this issue I encountered in my codes for a school assignment. Trying to make a Room Activity chart in a winform for a school project where the SQL COUNT query I input counts the rows that have the value 'Room Activity' under the Event column but for some odd reason, I receive an ArgumentException wasn't handled error that tells me Column with name 'Event' was not found.
What am I doing wrong with my code?
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.Windows.Forms.DataVisualization.Charting;
using System.Configuration;
using System.Data.SqlClient;
namespace Database_Chart_test
{
public partial class Form1 : Form
{
string strConnectionString = ConfigurationManager.ConnectionStrings["Database_Chart_test.Properties.Settings.LibrarySystemConnectionString"].ConnectionString;
public Form1()
{
InitializeComponent();
}
private void Activitychart_Click(object sender, EventArgs e)
{
}
private void RoomChart()
{
SqlConnection con = new SqlConnection(strConnectionString);
DataSet ds = new DataSet();
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity'", con);
adapt.Fill(ds);
Activitychart.DataSource = ds;
Activitychart.Series["WithActivity"].XValueMember = "Event";
Activitychart.Series["WithActivity"].YValueMembers = "Event";
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'librarySystemDataSet1.RoomsBooking' table. You can move, or remove it, as needed.
this.roomsBookingTableAdapter.Fill(this.librarySystemDataSet1.RoomsBooking);
// TODO: This line of code loads data into the 'librarySystemDataSet.Log' table. You can move, or remove it, as needed.
this.logTableAdapter.Fill(this.librarySystemDataSet.Log);
RoomChart();
}
}
}
After SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity' executed, it will return a table with 1 column and 1 row (the count number).
Query result:
So the cause of the ArgumentException is that there is no column named Event in ds.Tables[0].
If you want to get the count, just call ExecuteScalar Method
using (SqlConnection conn = new SqlConnection(strConnectionString))
{
string strSQL = "SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity'";
SqlCommand cmd = new SqlCommand(strSQL, conn);
conn.Open();
int count = (int)cmd.ExecuteScalar();
// add data point
Activitychart.Series["WithActivity"].Points.AddXY("Event", count);
Console.WriteLine("The count is {0}", count);
}
In addition, according to the code you provided, you are trying to use Event(a string) as YValueMembers. This does not seem reasonable. Generally, YValueMembers should be of numeric type.

C# ASP.NET - SImplify number of SQL queries written in code

Here's a little background on what I'm doing...
I'm writing a C# web app. On the main page, I have a data input form with about 25 individual Dropdownlists. I created a table called options, and it's pretty simple (ID, Category, Option). Each option I create is categorized so my query will only include options that match the category I'm looking up. Each Category matches one of the 25 Dropdownlists I need to populate.
So I'm able to get a few of these populated on the form and they work great. I'm concerned that the re-writing of this code (with slight variation of the DDlist name and category name) will cause the code to be much longer. Is there a way I can create a class of it's own and pass parameters to the class so it only returns me data from the correct category and populates the correct Dropdownlist? Here's some sample code I have so far for 2 DD fields. The DDStationList and DDReqeustType are the names of 2 of the 25 Dropdownlists I have created:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
namespace TEST
{
public partial class _Default : Page
{
//Main connection string
string SqlConn = ConfigurationManager.AppSettings["SqlConn"];
string qryRequestType = ConfigurationManager.AppSettings["qryRequestTypes"];
string qryStationNumbers = ConfigurationManager.AppSettings["qryStationNumbers"];
protected void Page_Load(object sender, EventArgs e)
{}
protected void BtnAddNew_Click(object sender, EventArgs e)
{
//GET Request Types
DataTable RequestTypes = new DataTable();
SqlConnection Conn = new SqlConnection(SqlConn);
{
SqlDataAdapter adapter = new SqlDataAdapter(qryRequestType, Conn);
adapter.Fill(RequestTypes);
DDRequestType.DataSource = RequestTypes;
DDRequestType.DataTextField = "Option";
DDRequestType.DataValueField = "Option";
DDRequestType.DataBind();
}
// Get Stations
DataTable Stations = new DataTable();
SqlConnection Conn = new SqlConnection(SqlConn);
{
SqlDataAdapter adapter = new SqlDataAdapter(qryStationNumbers, Conn);
adapter.Fill(Stations);
DDStationList.DataSource = Stations;
DDStationList.DataTextField = "Option";
DDStationList.DataValueField = "Option";
DDStationList.DataBind();
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
//More stuff to do here for submit code
}
}
}
Example queries from my config file that correspond to above code:
SELECT [Option] FROM Table WHERE Category = 'RequestType';
SELECT [Option] FROM Table WHERE Category = 'Station';
So, is it possible I can create a class that I can pass the Option's Category into that runs the query Like this:
SELECT [Option] FROM Table WHERE Category = #Category;
...and then populate the correct Dropdownlist (need to do this 25 times)?
If I'm not clear on my question, I'll be happy to explain further.
Why not create a stored procedure instead?
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_GetCategory", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Category", SqlDbType.VarChar).Value = txtCategory.Text;
con.Open();
var results = cmd.ExecuteReader();
}
}
OR include the parameter
string sql = "SELECT [Option] FROM Table WHERE Category = #Category";
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd= new SqlCommand(sql, con)) {
cmd.Parameters.Add("#Category", SqlDbType.VarChar).Value = txtCategory.Text;
con.Open();
var results = cmd.ExecuteReader();
}
}
EDIT
class Category
{
/* properties */
/* method */
public List<Category> GetCategory(string selectedCategory)
{ /* Method statements here */ }
}

I need to find the largest ID (prim key) in table, get the value & use it insert a new row in my table-need to use datasource1.SelectCommand

C# MSSql: I need to find the largest ID (primary key) in my table, get the value and use it to insert a new row in my table. I need to use datasource1.SelectCommand. I have tried sqlCommand, but that didn't work.
Below is the code as I have it so far:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Windows.Input;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project
{
public partial class ListProperty : System.Web.UI.Page
{
//Other code here (Page_LOad, Dropdown list, etc)
protected void OnButtnClick(object sender, EventArgs e)
{
string sqlProc1 = "SELECT row from PROPERTY ORDER BY Id DESC Limit 1";
//SqlDataAdapter MxID = new SqlDataAdapter(sqlProc1,SqlDataSource1.SqlCacheDependency);
//SqlDataSource1.SelectCommand = sqlProc1;
//SqlConnection sqlConnection1 = new SqlConnection();
EntityDataSource cmd = new EntityDataSource();
//SqlCommand cmd = new SqlCommand();
Object returnValue;
cmd.CommandText = sqlProc1;
//cmd.CommandType = System.Data.CommandType.Text;
//cmd.Connection = sqlConnection1;
//sqlConnection1.Open();
returnValue = cmd.CommandText;
//sqlConnection1.Close();
Object MxID = returnValue;
MxID.ToString();
int MxIDint = (Int32)MxID + 1;
String strMxID = MxIDint.ToString();
sqlProc1 = "INSERT INTO PROPERTY(ID,Property_ID,Type_ID,Coordinates) VALUES(" + strMxID + ",'1','1','0.')";
SqlDataSource1.SelectCommand = sqlProc1;
//GridView1.DataBind(); //generates error
}
}
}
Please help!
use this SQL query:
select MAX(id) from PROPERTY;
queryResult = dbContext.Database
.SqlQuery<int>("SELECT Max(Id) from PROPERTY ")
.Single();
Check this out for more details:get a scalar value
I solved this by using Joe's suggestion to make the Id key self increment. I had to figure out how do that on my own though. I tried it before but I tried again and it did.

compare the length of two variable

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++;
}

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