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 */ }
}
Related
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.
I want to show my data that I have stored in a SQLite database in an ASP.net page which I code in C#.
I searched a lot on the internet and in my previous question someone showed me a really helpfull article. I used the code but it still doesn't work.
What I want is to get the first three columns in my gridview. So "woord", "vertaling" and "gebruiker" from the table "tbWoorden" should be displayed in the gridview.
This is my code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Scripts_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTest_Click(object sender, EventArgs e)
{
string connectionString =
#"Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db";
using (var conn = new System.Data.SQLite.SQLiteConnection(connectionString))
{
conn.Open();
DataSet dsTest = new DataSet();
// Create a SELECT query.
string strSelectCmd = "SELECT woord,vertaling,gebruiker FROM tbWoorden";
// Create a SqlDataAdapter object
// SqlDataAdapter represents a set of data commands and a
// database connection that are used to fill the DataSet and
// update a SQL Server database.
SqlDataAdapter da = NewMethod(conn, strSelectCmd);
// Fill the DataTable named "Person" in DataSet with the rows
// returned by the query.new n
da.Fill(dsTest, "tbWoorden");
// Get the DataView from Person DataTable.
DataView dvPerson = dsTest.Tables["tbWoorden"].DefaultView;
// Set the sort column and sort order.
dvPerson.Sort = ViewState["SortExpression"].ToString();
// Bind the GridView control.
grdMijnLijsten.DataSource = dvPerson;
grdMijnLijsten.DataBind();
using (var command = new System.Data.SQLite.SQLiteCommand(conn))
{
command.Connection = conn;
command.CommandText =
#"SELECT[vertaling], [woord] FROM[tbWoorden] WHERE[woord] = 'ans'";
using (var reader = command.ExecuteReader())
{
string test = "";
}
}
}
}
private static SqlDataAdapter NewMethod(System.Data.SQLite.SQLiteConnection conn, string strSelectCmd)
{
return new SqlDataAdapter(strSelectCmd, conn);
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void grdMijnLijsten_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
The error I get is: cannot convert from 'System.Data.SQLite.SQLiteConnection' to 'string'.
The part that causes the error is the conn string in the NewMethod:
private static SqlDataAdapter NewMethod(System.Data.SQLite.SQLiteConnection conn, string strSelectCmd)
{
return new SqlDataAdapter(strSelectCmd, conn);
}
What do I have to change?
Thanks in advance, Elias
You have to use SQLiteDataAdapter (from the SQLite family) instead of SqlDataAdapter (which is part of the SQLClient family)
I am making a attendance system, and here is my problem now, after i searched for a name of a person and try to log him in for attendance, it is fine at first, after logging in the second name it is still fine. but once i tried to edit the login attendance of the first or second user, all the values in my datagridview(connected to my database) became duplicated. if i enter name1 for attendance in my week1 it is fine. name2 for attendance in week1 is still fine.
but if i edit the same name. or even go to the next week number, all of the saved values got duplicated based on my recent inputed name.
for inserting new records
SqlConnection cnn200 = new SqlConnection(connectionstring);
string sql200 = "SELECT * FROM attendance WHERE csign=#csign ";
cnn200.Open();
SqlCommand cmd200 = new SqlCommand(sql200, cnn200);
SqlDataReader rdr200;
cmd200.Parameters.AddWithValue("#csign", callsign);
rdr200 = cmd200.ExecuteReader();
if (rdr200.Read() == true)
{
SqlConnection cnn201 = new SqlConnection(connectionstring);
if (textBox89.Text == "1")
{
string sql201 = "insert INTO attendance
(csign,name,week1)" + "VALUES" + "(#csign,#name,#week1)";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#week1",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
if (textBox89.Text == "2")
{
string sql201 = "insert INTO attendance
(csign,name,week2)" + "VALUES" + "(#csign,#name,#week2)";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#week2",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
and for updating
else{
SqlConnection cnn201 = new SqlConnection(connectionstring);
if (textBox89.Text == "1")
{
string sql201 = "UPDATE attendance SET
name=#name,csign=#csign,week1=#week1";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#week1",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
if (textBox89.Text == "2")
{
string sql201 = "UPDATE attendance SET
name=#name,csign=#csign,week2=#week2";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#week2",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}`}
nica, I think I can help. What you are trying to do can be done easily with less coding lines. An entire DataGridView can be displayed, edited, deleted and have no duplicates by using a few more objects
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Globalization;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace ADO_NET_Testbed
{
public partial class MainForm : Form
{
private SqlDataAdapter adapter;
private string connectionString = #"Data Source=Server;Persist Security Info=True;Password=password!;User ID=sooperuser;Initial Catalog=Database";
private string sqlcommand = #"SELECT OPID, LastName, FirstName, Title, PhoneOffice, PhoneCell, Email, Active, Admin, Tester, Educator, Developer FROM AuditUser";
private SqlCommandBuilder cmdBuilder = new SqlCommandBuilder();
private DataTable datatable = new DataTable();
private DataSet dataset = new DataSet();
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
adapter = new SqlDataAdapter(sqlcommand, connectionString);
adapter.Fill(dataset, "AuditUser");
dgvUsers.DataSource = dataset.Tables[0];
dgvUsers.Enabled = true;
this.Show();
}
private void btnCancel_Click(object sender, EventArgs e)
{
dataset.Clear();
dataset.Reset();
this.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
cmdBuilder.DataAdapter = adapter;
adapter.Update(dataset.Tables[0]);
this.Close();
}
}
}
As a quick rundown of what is going on, the SqlDataAdapter holds the four queries, but auto-creates three from the SELECT command. Using a SqlCommandBuilder enables the other three to be added, although the debugger will not show them as anything but NULL. The adapter.Fill() and adapter.Update() handle all the different commands based on the RowState of each row in the datagridview. "Cancel" is overkill seeing as this form is closed anyway.
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
My method is not being called by my application. I've used breakpoints and it's never initiated in the code. I'm building a C# Windows Forms application using an Azure Database, but the DataGridView is never being filled neither is the code being called at all... I have noooo clue whatsoever why..
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.Data.SqlClient;
using System.Configuration;
namespace MyWinFormsProj
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings
["MyConnetion"].ConnectionString;
// Load all employees
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
// Crate company
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill out information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue(
"#companyName", textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
MessageBox.Show("Grattis! Du har skapat ett företag");
}
}
}
}
The second method is working and is doing what it is supposed to do, but the first one is never called..
you need to set an event handler on the gridView onLoad and pass this method to the handler
public void GridView_OnLoad(object sender, EventArgs e)
{
dataEmployees_Load();
}
You need to fix your method signature to look like this:
private void dataEmployees_Load(object sender, EventArgs e)
Then, in your GirdView, you need to set this function as handler for event "onload":
OnLoad="dataEmployees_Load"
Thank you guys for your answers it helped my solve the problem. Like you were saying the problem was in the method not being called. So I called it directly on initiliazeComponent like this.
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
Load += new EventHandler(dataEmployees_Load); //Added this code
}
// Load all employees
private void dataEmployees_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}