The data isn't being loaded into datagrid view. What am i missing? - sql

I think this is one of those times where I'm looking at the code and it all seems fine because my eye's think it will be. I need a fresh set of eyes to look at this code and tell me way it's not loading into the first datagrid view. Thank you for any help your able to provide.
private DataSet DataSetRentals { get; set; }
public DataRelationForm()
{
InitializeComponent();
}
private void DataRelationForm_Load(object sender, EventArgs e)
{
DataSet relationship = new DataSet("relationship");
/////
SqlConnection conn = Database.GetConnection();
SqlDataAdapter adapter = new SqlDataAdapter("Select * From Car", conn);
DataSet DataSetRentals = new DataSet("Relationship");
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Car");
adapter.Fill(DataSetRentals, "Car");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Car");
DataTable Car;
Car = DataSetRentals.Tables["Car"];
foreach (DataRow drCurrent in Car.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////////////////
SqlDataAdapter adapter2 = new SqlDataAdapter("Select * From CarRental", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Rentals");
adapter.Fill(DataSetRentals, "Rentals");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Rentals");
DataTable CarRental;
CarRental = DataSetRentals.Tables["Rentals"];
foreach (DataRow drCurrent in CarRental.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
/////
SqlDataAdapter adapter3 = new SqlDataAdapter("Select * From Customer", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Customer");
adapter.Fill(DataSetRentals, "Customer");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Customer");
DataTable Customer;
Customer = DataSetRentals.Tables["Customer"];
foreach (DataRow drCurrent in Customer.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////
DataSetRentals.Tables.Add(Customer);
DataSetRentals.Tables.Add(CarRental);
DataSetRentals.Tables.Add(Car);
DataRelation Step1 = new DataRelation("Customer2CarR",
Customer.Columns["CustomerNo"], CarRental.Columns["CustomerNo"]);
DataSetRentals.Relations.Add(Step1);
DataRelation Step2 = new DataRelation("CarR2Car",
Car.Columns["CarID"], CarRental.Columns["CarID"]);
DataSetRentals.Relations.Add(Step2);
////////////////////////
CustomerGrid.DataSource= DataSetRentals.Tables["Customer"];
CarRGrid.DataSource = DataSetRentals.Tables["CarRental"];
CarGrid.DataSource = DataSetRentals.Tables["Car"];
CustomerGrid.SelectionChanged += new EventHandler(Customer_SelectionChanged);
CarRGrid.SelectionChanged += new EventHandler(CarR_SelectionChanged);
}
private void Customer_SelectionChanged(Object sender, EventArgs e)
{
if (CustomerGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CustomerGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["CarRental"].DefaultView.RowFilter =
"CustomerNo = " + selectedRow.Row["CustomerNo"].ToString();
}
else
{
}
}
private void CarR_SelectionChanged(Object sender, EventArgs e)
{
if (CarRGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CarRGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["Car"].DefaultView.RowFilter =
"CarID = " + selectedRow.Row["CarID"].ToString();
}
}
And this is the code for the Database.GetConnection() method:
SqlConnectionStringBuilder stringBuilder = new SqlConnectionStringBuilder();
bool OnUni;
OnUni = (System.Environment.UserDomainName == "SOAC") ? true : false;
stringBuilder.DataSource = (OnUni) ? #"SOACSQLSERVER\SHOLESQLBSC" : "(local)";
stringBuilder.InitialCatalog = "CarRental_P117365";
stringBuilder.IntegratedSecurity = true;
return new SqlConnection(stringBuilder.ConnectionString);

It looks like you may have forgotten to call SqlConnection.Open() to actually open the connection. I would also recommend wrapping your connection in a using and explicitly calling SqlConnection.Close() at the end of it, so you don't accidentally leave it open:
using(SqlConnection conn = Database.GetConnection())
{
conn.Open();
/*
rest of code here
*/
conn.Close();
}
For some other good information/examples of properly opening/disposing of SqlConnections, you can also take a look at these SO questions:
Close and Dispose - which to call?
Do I have to Close() a SQLConnection before it gets disposed?
in a "using" block is a SqlConnection closed on return or exception?

youre not binding your data to any datasoruce.
try something like this
using(SqlConnection conn = Database.GetConnection())
try
{
{
------your code here up to DataTable Car-----
DataTable Car;
Car = DataSetRentals.Tables["Car"];
gridview.Datasource = Car;
}
}
catch (SqlException sqlex )
{
string msg = "Fetch Error:";
msg += sqlex.Message;
throw new Exception(msg);
}
Theres no need to open or close the SQL connection as this is done using the using statement at the top where it opens, and when its finishes closes \ disposes of the connection

Related

How do I define a data source for a panel?

I was trying to display a table that is being saved in my sql server and I wanted it to be displayed in my panal but it kept showing this error saying 'panel' doesnot contain a definition for 'Datasource' and no extension method 'datasource' accepting a first argument of type 'panel' could be found (are you missing a using directive or an assembly reference?) please help..
public partial class Form17 : Form
{
public Form17()
{
InitializeComponent();
ShowTGBtbl();
}
private void button5_Click(object sender, EventArgs e)
{
}
private void Form17_Load(object sender, EventArgs e)
{
int w = Screen.PrimaryScreen.Bounds.Width;
int h = Screen.PrimaryScreen.Bounds.Height;
this.Location = new Point(0, 0);
this.Size = new Size(w, h);
}
SqlConnection Con = new SqlConnection(#"Data Source=LAPTOP-9514GUKU\SQLEXPRESS;Initial Catalog=Mydatabase.com;Integrated Security=True");
private void ShowTGBtbl()
{
Con.Open();
string Query = "select * from TGBtbl";
SqlDataAdapter sda = new SqlDataAdapter(Query, Con);
SqlCommandBuilder Builder = new SqlCommandBuilder(sda);
var ds = new DataSet();
sda.Fill(ds);
TGBoverall.Datasource = ds.Tables[0];
Con.Close();
}

DataAdapter.Update not updating

hey hope someone can help, going crazy :-)
doing a little program that gets dataset and updates it again, i have the following SQLclass. Dataset is traversing fine and values are changed but it dosnt commit to DB.
class SQLConnection
{
private string SQL_String;
private string strCON;
System.Data.SqlClient.SqlDataAdapter da_1;
public string Sql {
set { SQL_String = value; }
}
public string connection_string
{
set { strCON = value; }
}
public System.Data.DataSet Getconnection
{
get { return Getmydataset(); }
}
private System.Data.DataSet Getmydataset()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCON);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(SQL_String, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_Data_1");
return dat_set;
}
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1);
int test = cb.DataAdapter.Update(ds.Tables[0]);
}
}
}
When i call the class and try to do update the DataAdapter returns 0
static public void Main(string[] args)
{
GetClosedComputers();
}
getclosedcomputers
public static DataSet GetClosedComputers()
{
try
{
SQLConnection objConnect = new SQLConnection();
conString = Properties.Settings.Default.Connectionstring;
objConnect.connection_string = conString;
//call stored procedure
objConnect.Sql = Properties.Settings.Default.GetNextClosedComputers;
ds = objConnect.Getconnection;
ds.Tables[0].Columns["State"].Expression = "'1'";
objConnect.UpdateDatabase(ds);
}
catch (Exception e)
{
ErrorString = e.Message;
}
return ds;
}
Hmm seemed like i had to issues, first of i couldnt use an UpdateProcedure, which i not sure why and also the ".Expression" could be used, this solved it.
objConnect = new SQLConnection();
conString = Properties.Settings.Default.Connectionstring;
objConnect.connection_string = conString;
// use sql query instead of stored procedure!!!
objConnect.Sql = Properties.Settings.Default.Test;
//Dataset with all computers
ds = objConnect.Getconnection;
//DataSet results = StartStopVM.StartVirtualMachines(ds);
DataTable dt = ds.Tables[0];
//this didnt work
//ds.Tables[0].Columns["State"].Expression = "'1'";
//
foreach(DataRow dr in dt.Rows)
{
dr["State"] = 1;
}
objConnect.UpdateDatabase(ds);

Get value from list and show to a label

I'm creating a search engine based on SQL database.
Is it possible to get sql data on a List and then show data on labels?
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=SHKELQIM\SQLEXPRESS;Initial Catalog=Dictionary;Integrated Security=True");
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT Word FROM Dictionary WHERE Word like'%" + lblsearch.Text + "%'", con);
DataSet ds = new DataSet();
da.Fill(ds, "Dictionary");
List<string> word = new List<string>();
foreach (DataRow row in ds.Tables["Dictionary"].Rows)
{
word.Add(row["Word"].ToString());
}
Label1.Text = word[0].ToString();
}
catch (SqlException ex)
{
Label1.Text = ex.Message;
}
finally
{
con.Close();
}
}
}
}
I get an ArgumentOutOfRangeException at line - Label1.Text = word[0].ToString();
I don't know why, because that column contains data.
Also how can I position labels where I want, if I need to create new labels for every word?

How do I print SQL query using MessageBox in C#

I am stuck with this problem since yesterday. I have created a button, which when clicked display the results from a SQL Server table. I thought of using MessageBox to print these results or if there is any other way to print results?
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * FROM Products", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
command.ExecuteNonQuery();
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
I have tried different methods but it never worked.. I am really stuck. If you want more details, let me know. Thanks for the help in advance
Add a datagridview control to show multiple rows and try this code and rename it what you want and replace this YourDataGridVeiwName from the name you set for datagridview control and try below code
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
DataTable dt = new DataTable();
sda.Fill(dt);
YourDataGridVeiwName.DataSource= dt;
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
You need to use the SqlDataReader and iterate over the rows returned, extract what you need from each row, and then display that to the enduser.
I modified your code a bit, to make it safer (using blocks!), and I modified the query to return only the product name (assuming you have that) since you cannot really display a whole row in a message box....
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string productName = reader.GetFieldValue<string>(0);
MessageBox("Product is: " + productName);
}
reader.Close();
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}

Loading data from SQL Server into C# application

I have some problem accessing my data from a SQL Server database via C# application. I have a small project to make and I can't go further because my data is loading in. I try to load it in a DataGridView.
Here are some code examples:
public List<Country> GetCountryList()
{
string query = "SELECT * FROM Orszag", error = string.Empty;
SqlDataReader rdr = ExecuteReader(query, ref error);
List<Country> countryList = new List<Country>();
if (error == "OK")
{
while (rdr.Read())
{
Country item = new Country();
item.CountryId = Convert.ToInt32(rdr[0]);
item.CountryName = rdr[1].ToString();
countryList.Add(item);
}
}
CloseDataReader(rdr);
return countryList;
}
This is where I put my data in a list
private void FillDgvGames()
{
dgvGames.Rows.Clear();
List<Country> CountryList = m_Country.GetCountryList();
foreach (Country item in CountryList)
{
dgvGames.Rows.Add(item.CountryId,item.CountryName);
}
}
And this is where I retrieve it ... I have to make the same thing with 8 more tables but this is the simplest and I thought it's easier this way.... if someone can help me I'd appreciate it ...
PS:
This is the execute reader
protected SqlDataReader ExecuteReader(string query, ref string errorMessage)
{
try
{
OpenConnection();
SqlCommand cmd = new SqlCommand(query, m_Connection);
SqlDataReader rdr = cmd.ExecuteReader();
errorMessage = "OK";
return rdr;
}
catch (SqlException e)
{
errorMessage = e.Message;
CloseConnection();
return null;
}
}
And this is the connection string
protected string m_ConnectionString = "Data Source=SpD-PC;Initial Catalog=master;Integrated Security=SSPI";
Are you setting the data source of your DataGridView?
dgvGames.DataSource = CountryList;