How to put search result of a query in variables in C#? - c#

I want to search some input in a data table and if exact data is found then I want to put those data into another table. If not, I will simply clear the corresponding TextBox. I have done theses so far.
private void btn_InputConfirm_Click(object sender, EventArgs e) {
string strConnection = #"Data Source=F_NOOB-PC\;Initial Catalog=ComShopDB;Integrated Security=True";
SqlConnection objcon = new SqlConnection(strConnection);
try {
string strcmd1 = "SELECT partID,partAvailable FROM Parts WHERE partID LIKE '" + txtbox_ProductSerial.Text + "'AND partAvailable ='yes'";
SqlCommand objcmd1 = new SqlCommand(strcmd1, objcon);
objcon.Open();
objcmd1.ExecuteNonQuery();
objcon.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
Some help will be very much appreciated. Thanks in advance.

You can use a DataTable, use ExecuteReader method and load all records into DataTable, then use AsEnumerable and some LINQ you can get your results as a List.
DataTable dt = new DataTable();
var reader = objcmd1.ExecuteReader();
if(reader.HasRows)
{
dt.Load(reader);
var myValues = dt.AsEnumerable()
.Select(d => new {
Id = d["partID"],
Available = d["partAvailable"]
}).ToList();
}
Also you should consider using parameterized queries instead to prevent SQL Injection Attacks.

The easiest is to use DataAdapter and then use its Fill() function on a DataTable or DataSet. You do not need to open and close the connection as the Fill() function will do that for you:
private void btn_InputConfirm_Click(object sender, EventArgs e)
{
string strConnection = #"Data Source=F_NOOB-PC\;Initial Catalog=ComShopDB;Integrated Security=True";
SqlConnection objcon = new SqlConnection (strConnection);
try
{
//Writing command//
string strcmd1 = "SELECT partID,partAvailable FROM Parts WHERE partID LIKE '" + txtbox_ProductSerial.Text + "'AND partAvailable ='yes'";
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(strcmd1, objcon);
System.Data.DataSet ds = new System.Data.DataSet();
aa.Fill(ds);
}
catch ( Exception ex )
{
MessageBox.Show (ex.Message);
}

Related

Updating/saving data to an SQL database table using c# winforms

I'll start off by saying that I'm pretty inept at coding (have yet to learn how to utilize classes and how they work in depth), and that I've never worked with sql before doing this project.
The idea here is that you connect to an sql database, after which a datagridview element gets filled with data from a table called TABLE_1 by default. The user should then be able to input, delete and save data.
The first two work operations work perfectly, but the saving is the problem. I've banged my head against a wall for about 4 days trying to get the saving to work, but I just cant get it to do so. The saving is done with the method Button3_click.
Any insight as to what I should do?
Is the main chunk of the code where you connect the part where I'm
messing up?
//initialize the classes I guess, on some youtube guides they did so
SqlConnection con;
DataSet ds;
SqlDataAdapter a;
DataTable t;
SqlCommandBuilder scb;
static string tablename = "TABLE_1";
string constring;
//connect button
private void button1_Click(object sender, EventArgs e)
{
try
{
//connect using info from textboxes, connection is ok
constring = "server=" + Server.Text + ";database=" + DB.Text + ";UID=" + UID.Text + ";password=" + Password.Text;
SqlConnection con = new SqlConnection(constring);
con.Open();
DataSet ds = new DataSet();
Save.Enabled = true;
//check if table name is empty, if so default to TABLE_1
if (textBox1.Text != "")
{
tablename = textBox1.Text;
}
else
{
tablename = "TABLE_1";
}
a = new SqlDataAdapter("SELECT * FROM " + tablename, con);
DataTable t = new DataTable();
a.Fill(t);
datagrid.DataSource = t;
//
label5.Text = Server.Text;
con.Close();
}
catch(Exception es)
{
MessageBox.Show(es.Message);
}
}
//save button
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
con.Open();
DataSet ds = new DataSet();
DataTable t = new DataTable();
a.TableMappings.Add(tablename, "t");
scb = new SqlCommandBuilder(a);
a.Update(t);
con.Close();
}
Use the following example which sets up the adapter, dataset and table name as private variables.
Also, I recommend to never use one letter variable names as a) it's difficult to debug b) when getting into more lines of code it's going to be difficult to know what a variable is for.
Next up, using SELECT *, it' unknown if you have setup a auto-incrementing primary key which is needed to perform updates. In the example below, Id is auto-incrementing.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsDataAdapterExample
{
public partial class Form1 : Form
{
private SqlDataAdapter _companiesSqlDataAdapter;
private DataSet _companiesDataSet;
private string _tableName = "Companies";
public Form1()
{
InitializeComponent();
Shown += OnShown;
}
private void OnShown(object sender, EventArgs e)
{
_companiesDataSet = new DataSet();
_companiesSqlDataAdapter = new SqlDataAdapter(
"SELECT Id, FirstName, LastName, PhoneNumber, City FROM dbo.Companies;",
"Data Source=.\\sqlexpress;Initial Catalog=ForumExample;" +
"Integrated Security=True");
var builder = new SqlCommandBuilder(_companiesSqlDataAdapter);
_companiesSqlDataAdapter.Fill(_companiesDataSet, _tableName);
dataGridView1.DataSource = _companiesDataSet.Tables[_tableName];
}
private void SaveButton_Click(object sender, EventArgs e)
{
_companiesSqlDataAdapter.Update(_companiesDataSet, _tableName);
}
}
}

Eliminating an option from a ComboBox (2), based on the input of the first ComboBox (1) c#

I am creating an airline booking system and I have 2 combo boxes. The first is for Departure City and the second is for Arrival City. I want to be able to eliminate the choice in the first combo box from the second, as I don't want the same city to be able to be submitted as both the departure and arrival city. I am querying the city names from a database.
Here is my code:
public partial class main : Form
{
public main()
{
InitializeComponent();
string connectionString = #"Base Schema Name=cyanair;data source=C:\Users\Client 0819\source\repos\Cyanair\cyanair.db";
//Departure ComboBox
SQLiteConnection conn = new SQLiteConnection(connectionString);
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM CyanairAirports";
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboDeparture.DataSource = dt;
comboDeparture.ValueMember = "Descriptions";
comboDeparture.DisplayMember = "Descriptions";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Arrival ComboBox
private void comboDeparture_DisplayMemberChanged(object sender, EventArgs e)
{
string connectionString = #"Base Schema Name=cyanair;data source=C:\Users\Client 0819\source\repos\Cyanair\cyanair.db";
SQLiteConnection conn = new SQLiteConnection(connectionString);
**String city = comboDeparture.DisplayMember;**
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM CyanairAirports WHERE Descriptions IS NOT '" + comboDeparture.SelectedValue.ToString() + "'";
richTextBox1.Text = "SELECT * FROM CyanairAirports WHERE Descriptions IS NOT '" + comboDeparture.SelectedValue + "'";
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboArrival.DataSource = dt;
comboArrival.ValueMember = "Descriptions";
comboArrival.DisplayMember = "Descriptions";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks :)
It looks like you're handling the DisplayMemberChanged event on comboDeparture, and trying to update the values of comboArrival in that handler. However, DisplayMemberChanged only triggers when the DisplayMember property changes.
DisplayMember only tells the control which property to display on a data bound control. It isn't tied to the index or value selected in the ComboBox. So, the only time the code to populate comboArrival runs is in the constructor when you set comboDepartarture.DisplayMember. Instead, handle either ComboBox.SelectedIndexChanged or ComboBox.SelectedValueChanged and set the items of comboArrival.
A few other important things to note about your code.
First, you should use a parameterized query when running Sql Statements, rather than concatenating strings. Concatenating strings as you're doing opens you up to SQL Injection Attacks. I'm not familiar with SqlLite and can't provide you with an example of how to modify your code, but perhaps this question can help.
Second, you don't need to re-run the query every time you change the selected value in comboDeparture. Just add comboArrival's data source as a field on the Form and you can filter it. For example...
public partial class main : Form
{
// Your constructors...
private void comboDepartures_SelectedIndexChanged(object sender, EventArgs e)
{
if (_arrivalsDataSource == null)
{
_arrivalsDataSource = new System.Data.DataTable();
// Load _arrivalsDataSource from the database, basically how you're doing it now.
comboArrival.DataSource = _arrivalsDataSource.DefaultView;
comboArrival.DisplayMember = "Descriptions"
comboArribal.ValueMember = "Descriptions"
}
if (comboDeparture.SelectedIndex == -1)
{
_arrivalsDataSource.DefaultView.RowFilter = null; // Clear the filter.
}
else
{
// Set the filter.
_arrivalsDataSource.DefaultView.RowFilter = $"Description <> '{comboDeparture.SelectedValue}'";
}
}
private System.Data.DataTable _arrivalsDataSource = null;
}

Filling a DataTable in C# using MySQL

I'm attempting to fill a DataTable with results pulled from a MySQL database, however the DataTable, although it is initialised, doesn't populate. I wanted to use this DataTable to fill a ListView. Here's what I've got for the setting of the DataTable:
public DataTable SelectCharacters(string loginName)
{
this.Initialise();
string connection = "0.0.0.0";
string query = "SELECT * FROM characters WHERE _SteamName = '" + loginName + "'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query,connection);
DataTable dt = new DataTable("CharacterInfo");
returnVal.Fill(dt);
this.CloseConnection();
return dt;
}
else
{
this.CloseConnection();
DataTable dt = new DataTable("CharacterInfo");
return dt;
}
}
And for the filling of the ListView, I've got:
private void button1_Click(object sender, EventArgs e)
{
string searchCriteria = textBox1.Text;
dt = characterDatabase.SelectCharacters(searchCriteria);
MessageBox.Show(dt.ToString());
listView1.View = View.Details;
ListViewItem iItem;
foreach (DataRow row in dt.Rows)
{
iItem = new ListViewItem();
for (int i = 0; i < row.ItemArray.Length; i++)
{
if (i == 0)
iItem.Text = row.ItemArray[i].ToString();
else
iItem.SubItems.Add(row.ItemArray[i].ToString());
}
listView1.Items.Add(iItem);
}
}
Is there something I'm missing? The MessageBox was included so I could see if it has populated, to no luck.
Thanks for any help you can give.
Check your connection string and instead of using
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query,connection);
DataTable dt = new DataTable("CharacterInfo");
returnVal.Fill(dt);
this.CloseConnection();
return dt;
you can use this one
MySqlCommand cmd = new MySqlCommand(query, connection);
DataTable dt = new DataTable();
dt.load(cmd.ExecuteReader());
return dt;
Well, I ... can't figure out what you have done here so I'll paste you my code with which I'm filling datagridview:
1) Connection should look something like this(if localhost is your server, else, IP adress of server machine):
string connection = #"server=localhost;uid=root;password=*******;database=*******;port=3306;charset=utf8";
2) Query is ok(it will return you something), but you shouldn't build SQL statements like that.. use parameters instead. See SQL injection.
3) Code:
void SelectAllFrom(string query, DataGridView dgv)
{
_dataTable.Clear();
try
{
_conn = new MySqlConnection(connection);
_conn.Open();
_cmd = new MySqlCommand
{
Connection = _conn,
CommandText = query
};
_cmd.ExecuteNonQuery();
_da = new MySqlDataAdapter(_cmd);
_da.Fill(_dataTable);
_cb = new MySqlCommandBuilder(_da);
dgv.DataSource = _dataTable;
dgv.DataMember = _dataTable.TableName;
dgv.AutoResizeColumns();
_conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (_conn != null) _conn.Close();
}
}
So, every time I want to display some content of table in mysql database I call this method, pass query string and datagridview name to that method. and, that is it.
For your sake, compare this example with your and see what can you use from both of it. Maybe, listview is not the best thing for you, just saying ...
hope that this will help you a little bit.
Debug your application and see if your sql statement/ connection string is correct and returns some value, also verify if your application is not throwing any exception.
Your connection string is invalid.
Set it as follows:
connection = "Server=myServer;Database=myDataBase;Uid=myUser;Pwd=myPassword;";
Refer: mysql connection strings
Here the following why the codes would not work.
Connection
The connection of your mySQL is invalid
Query
I guess do you want to search in the table, try this query
string query = "SELECT * FROM characters WHERE _SteamName LIKE '" + loginName + "%'";
notice the LIKE and % this could help to list all the data. for more details String Comparison Functions

How to pass modified table name in SQL connection in ASP

I'm using SQL Server 2008 as my database in asp.net. And I'm passing the table name while at the time of clicking the <a> tag to web form. So how can I achieve this thing that when I click any link it change its sql query according to the value it receive?
For example:
<li class="last">
Item 1.1
</li>
Here cat contains the table name and sub contains the condition name.
And at the other side I'm doing:
SqlConnection con=new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag");
SqlDataAdapter da;
DataSet ds=new DataSet();
static DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
da = new SqlDataAdapter("select * from Architect where subcategory3='" + s1 + "'",con);
da.Fill(ds,"tab");
dt = ds.Tables["tab"];
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
}
}
So I just want that insted of giving table name Architect I just want to pass s - how can I do that?
I would suggest that you think of other solution for this because what you are currently doing will lead to a very simple SQL Injection and your database will be at a great risk. I suggest that you have an enum of all tables and pass the id of the table in the query string instead of the table name and also you should make sure that the condition string is valid from any sql injection before making the string concatination
Your design isn't really optimal; is it possible to consider storing all data in a central table linked to both Category and SubCategory?
There are several weaknesses; any string concatenation of sql leaves you open to SqlInjection attacks. Even if you are choosing values from drop down lists, for example, it is still possible for client side script to modify the values in your combo boxes, or for an attacker to simply post data to your server side event handler.
In addition, having to source data from several tables means that you may have to deal with different schemas in your results; if you expect this (i.e. some tables will have more columns than others) then you can handle it appropriately.
Your query would then become something similar to:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
if(String.IsNullOrEmpty(s) || String.IsNullOrEmpty(s1)) { return; } //Improve Validation and error reporting
using(SqlConnection conn = new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag"))
{
using(SqlCommand command = new SqlCommand(conn))
{
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM Table WHERE Category = #Category AND SubCategory = #SubCategory";
command.Parameters.Add(new SqlParameter() { Type = SqlDbType.String, Name = "#Category", Value = s });
command.Parameters.Add(new SqlParameter() { Type = SqlDbType.String, Name = "#SubCategory", Value = s1 });
conn.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
DataTable data = new DataTable("MyData");
data.Load(reader);
DataGrid1.DataSource = data;
DataGrid1.DataBind();
}
}
}
}
}
If you are stuck with your original model, then you may want to whitelist the table names so you can stick with parameterised queries:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
if(String.IsNullOrEmpty(s) || String.IsNullOrEmpty(s1)) { return; } //Improve Validation and error reporting
using(SqlConnection conn = new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag"))
{
using(SqlCommand command = new SqlCommand(conn))
{
command.CommandType = CommandType.Text;
switch(s)
{
case "Architect":
command.CommandText = "SELECT * FROM Architect WHERE SubCategory = #SubCategory";
break;
case "SomethingElse":
command.CommandText = "SELECT * FROM SomethingElse WHERE SubCategory = #SubCategory";
break;
default:
return; //Again, improve error handling
}
command.Parameters.Add(new SqlParameter() { Type = SqlDbType.String, Name = "#SubCategory", Value = s1 });
conn.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
DataTable data = new DataTable("MyData");
data.Load(reader);
DataGrid1.DataSource = data;
DataGrid1.DataBind();
}
}
}
}
}
One comment I would make though, is that even if you implement either of the examples above, you still have a big problem; your data access code, business logic, and presentation code are all now munged into the code behind for this page. You will have to repeat this everywhere you need it leading to plenty of duplication, which is especially a problem when you need to fix bugs.
Instead, you might consider creating classes or using an ORM to handle all of this work for you, so you instead request a list of Architect objects, or a list of SomethingElse from a class or component, thus leaving the aspx to deal with the presentation. There is also a discussion here about why you might not want to use an ORM.
If you follow this route, your code might then become something like:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
//Still do validation on s and s1
ObjectFactory of = new ObjjectFactory();
DataGrid1.DataSource = ObjectFactory.GetObjects(s, s1);
DataGrid1.DataBind();
}
}
Effectively, it is now someone else's job to worry about how to get the objects, and to collect them, vastly reducing the code you have in your code behind. Plus you can easily reuse that across a wide variety of interfaces!
da = new SqlDataAdapter("select * from " + s + " where subcategory3='" + s1 + "'",con);
Like this ?
SqlConnection con=new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag");
SqlDataAdapter da;
DataSet ds=new DataSet();
static DataTable dt=new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
da = new SqlDataAdapter("select * from '"+s+"' where subcategory3='" + s1 + "'",con);
da.Fill(ds);
dt = ds.Tables[0];
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
}
}

Find current day of week in c# ASP.Net

I want to find current day of week in c# ASP.Net like:
System.DateTime.Now.DayOfWeek.ToString();
This code works well in a console application, but when I try to store the value of this line in a string in ASP.Net website it returns nothing.
Can anyone help?
StringBuilder message = null;
protected void Page_Load(object sender, EventArgs e)
{
var dayofweek = System.DateTime.Now.DayOfWeek.ToString();
String conn = "Data Source=.;Initial Catalog=OCSI;Integrated Security=True";//conne
SqlConnection sqlconne = new SqlConnection(conn);
string selectSQL = "SELECT lec FROM schedule WHERE [day]='" + dayofweek +"'";
SqlCommand cmd = new SqlCommand(selectSQL, sqlconne);
SqlDataReader reader = null;
try
{
sqlconne.Open();
reader = cmd.ExecuteReader();
message = new StringBuider();
while (reader.Read())
{
message.Append(reader["lec"].ToString());
//question what are you using message for ...?
Label3.Text = dayofweek;
}
reader.Close();
}
catch (Exception ex)
{
Response.Write(ex.Mesage);
}
finally
{
sqlconne.Close();
// you neeed to Dispose of all other objects here too
// StringBuilder Object
// SqlDataReader Object
//SqlCommand Object..
//Look into wrapping your Connection / Command Sql Dataobject around a using() {}
}
I want to use current day in where clause SQL Query to get data relevant to current day from database table.
I used var as
protected void Page_Load(object sender, EventArgs e)
{
String conn = "Data Source=.;Initial Catalog=OCSI;Integrated Security=True";//conne
SqlConnection sqlconne = new SqlConnection(conn);
var testDay = DateTime.Now.DayOfWeek.ToString();
// string selectSQL = "SELECT lec FROM schedule WHERE [day]='" + dayofweek +"'";
string selectSQL = string.Format("SELECT lec FROM schedule WHERE [day]= {0}", testDay);
SqlCommand cmd = new SqlCommand(selectSQL, sqlconne);
SqlDataReader reader;
try
{
sqlconne.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
message += reader["lec"].ToString();
Label3.Text = testDay;
}
reader.Close();
}
catch
{
}
finally
{
sqlconne.Close();
}
It works fine for me.
Wep page is the value defined as a public , static, or property..
if you write
var testDay = DateTime.Now.DayOfWeek.ToString();
the results will = "Friday";
if everything is working fine when you remove the where clause then change the Where clause to be something like this
string selectSQL = string.Format("SELECT lec FROM schedule WHERE dbo.schedule.day = {0} ", testDay);
I would also change the name of the field day to something like DayName or something if day is a Reserved word don't use it..
look at this link for Reserved Words in SQL Reserved SQL Words
Also try changing your sql string to this
string selectSQL =
string.Format("SELECT lec FROM schedule WHERE [day]= {0}", dayofweek);
As an integer value (system sets sunday's as 0) =
int day = (int)DateTime.Now.DayOfWeek;

Categories

Resources