How does one assign column names to tables in dataset? - c#

I have this code
SqlConnection conn = Database.GetConnection();
//not sure why doing this bit (bit between this comment and next
//SqlDataAdapter adapter = new SqlDataAdapter("Select * From CarType", conn);
DataSet DataSetRentals2 = new DataSet("CustomerSQLTable");
DataTable table = new DataTable("CustomerSQLTable"); //you can name it
DataTable table2 = new DataTable("CarRental");
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = new SqlCommand("SELECT * FROM Customer", conn);
conn.Open();
///this might brake the code
///
adapter.Fill(DataSetRentals2,"CustomerSQLTable");
adapter.SelectCommand = new SqlCommand("SELECT * FROM CarRental", conn);
adapter.Fill(DataSetRentals2, "CarRental");
adapter.Fill(DataSetRentals2, "CarRental");
}
CustomerGrid.DataSource = DataSetRentals2;
CustomerGrid.DataMember = "CustomerSQLTable";
CarRGrid.DataSource = DataSetRentals2.Tables["CarRental"];
CarRGrid.DataMember = "CarRental";
the teacher gave me this code to link them in a relationship so that when i click on one customer number in one data grid and for it to only return corresponding records in the other.
DataRowView selectedRow =
(DataRowView)CustomerGrid.SelectedRows[0].DataBoundItem;
DataSetRentals2.Tables["CarRental"].DefaultView.RowFilter =
"CustomerNo = " + selectedRow.Row["CustomerNo"].ToString();.
so what i think i need to do is to name the columns in the dataset. But i have no idea how to do this. I'm sure there must be a way an I'm sure you guy's can easily tell me it. Thank you in advanced.

dataTable.Columns[0].ColumnName = "MyColumnName";

Your columns will already have names. They are supplied by the database.
I would guess that your issue is with this line. If this isn't it please describe what you're expecting to happen, vs what is actually happening so that we may assist you better.
CarRGrid.DataSource = DataSetRentals2.Tables["CarRental"];
Which should probably be
CarRGrid.DataSource = DataSetRentals2;

Related

How to sort and rank and select a unique value?

I need to get the rank, from a group of players by sorting using sql query.
i have the query.
query = #"SET #rank=0;
SELECT player_ID,player_name,HP,#rank:=#rank+1 As Rank
FROM player_profile ORDER BY HP DESC;"
the problem is i just need the specified player's rank from this query.
Since rank is generated using SQL, i can't use WHERE clause. That will one bring one player from DB, resulting one rank.
I tried to get all of them into a datatable and then filter the single value out of it.
con.Open();
MySqlDataAdapter dt = new MySqlDataAdapter();
DataTable tt = new DataTable();
string query = #"SET #rank=0;
SELECT player_ID,player_name,HP,#rank:=#rank+1 As Rank
FROM player_profile ORDER BY HP DESC;";
MySqlCommand cm1 = new MySqlCommand(query, con);
dt.SelectCommand = cm1;
dt.Fill(tt);
con.Close();
DataRow[] foundRows = tt.Select("player_name=" + Label2.Text); // Error:Cannot find column ["Column name"]
foreach (DataRow dr in foundRows)
{
Label32.Text = dr["Rank"].ToString();
}
this is how my table looks
http://pastebin.com/7KWJ9bn3
any help is appreciated.
I'm a big proponent of not putting business logic in your SQL which it seems like your doing here. The below code is my updated version of your code which should be logically equivalent without having to do any calculation on the SQL side of things.
I'm not entirely sure what you are trying to achieve (is this example code?) so if you can provide more info I can refine this some more, but again this will do the exact same thing in a "better" fashion.
con.Open();
MySqlDataAdapter dt = new MySqlDataAdapter();
DataTable tt = new DataTable();
string query = #"SET #rank=0;
SELECT player_ID,player_name,HP
FROM player_profile ORDER BY HP DESC;";
MySqlCommand cm1 = new MySqlCommand(query, con);
dt.SelectCommand = cm1;
dt.Fill(tt);
con.Close();
DataRow[] foundRows = tt.Select("player_name=" + Label2.Text); // Error:Cannot find column ["Column name"]
int count = 1;
foreach (DataRow dr in foundRows)
{
Label32.Text = count;//dr["Rank"].ToString();
count++;
}
What about selecting from the resulting table?
string query = #"SET #rank=0;
Select a.Rank from (SELECT player_ID,#rank:=#rank+1 As Rank
FROM player_profile ORDER BY HP DESC) a where player_ID=#1";

how can I display a dataBase Table in my multiple column comboBox

I am using multi column in combo box. So,I would like to display a database table like this photo.
I tried the below coding but I get only the table date without the table borders.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
req = "select id_amort_fiscal+''+amort_fiscal as combined from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
this is what I get as a result:
any Help please and thanks :D
Is this third party control?
Anyway your query is showing you are only picking 1 column. Try adding more columns in query.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
// *******************
// See the new_column2, new_column3 in the below query, replace them
// with your own columns
// ********************
req = "select id_amort_fiscal+''+amort_fiscal as combined, new_column2, new_column3 from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
Make sure you have assigned ColumnToDisplay property to your MultiColumnCombobox.
multiColumnComboBox1.ColumnsToDisplay = new String[] {"Combinded Fiscal", "First Name"};
This will bind your column data into particular column. To display the proper column header, I preferred to specify alias in your sql query and try to add more columns in your query.
req = "select (id_amort_fiscal+''+amort_fiscal) As [Combinded Fiscal], FName As [First Name] from amortissementFiscal;";

SqlDataReader filling column in datagridview

I have been wondering for quiet long time how can I set my SqlDataReader to fill column "pocet" in my datagridview "dtg_ksluzby". I thought that my code should look something like this:
SqlCommand novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz WHERE id='"+vyberradek+"'",spojeni); // I also have column "pocet" in table klisluz, vyberradek is string which selectrs id number
spojeni.Open();
SqlDataReader precti2 = novyprikaz2.ExecuteReader();
if (precti2.Read())
{
dtg_ksluzby.Columns["pocet"]; // this part I need to improve to fill
}
Would you please help me to improve my code?
Thanks so much in advance.
Edit for trippino:
In "klisluz" which is in the table that includes columns
(id,akce,subkey,text,pocet). I need to:
select * from klisluz where subkey = '"+vyberradek+"'
Take column pocet and fill it into dtg_ksluzby where i find the text is similar in column "text" in dtg_ksluzby
I hope my description is understandabla, sorry for my weak english.
Do not use string concatenation to build sql commands, (to avoid Sql Injection and parsing problem)
using(SqlConnection spojeni = new SqlConnection(conString))
using(SqlCommand novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz " +
"WHERE id = #id",spojeni);
{
novyprikaz2.Parameters.AddWithValue("#id", vyberradek);
spojeni.Open();
using(SqlDataAdapter da = new SqlDataAdapter(novyprikaz2))
{
DataTable dt = new DataTable();
da.Fill(dt);
dtg_ksluzby.DataSource = dt;
}
}
Use a DataAdapter to load your data from database and pass this DataAdapter instance to the DataSource of your DataGridView
Use something like this:
for (int i = 0; i < dtg_ksluzby.Rows.Count; i++)
{
var row = dtg_ksluzby.Rows[i];
using(var novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz WHERE text LIKE #t AND subkey=#s", spojeni))
{
novyprikaz2.Parameters.AddWithValue("#t", row.Cells["text"].Value.ToString());
novyprikaz2.Parameters.AddWithValue("#s", vyberradek);
spojeni.Open();
SqlDataReader precti2 = novyprikaz2.ExecuteReader();
if (precti2.Read())
{
row.Cells["pocet"].Value = precti2["pocet"];
}
}
}

how to use Dataset with aggregate function in asp.net c#

I have to find max value of one table using dataset.
I have written code for that as follows :
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select max(FlightBookingID) from dbo.FlightBookingDetails", FlyCon);
da.Fill(ds);
if (ds != null)
{
Session["FBookingID"] = Convert.ToString(ds.Tables[0].Rows[0]["FlightBookingID"]);
}
But its geting error in
Convert.ToString(ds.Tables[0].Rows[0]["FlightBookingID"]);
What changes should i do in above code?
Why can't you use SqlCommand.ExecuteScalar?
using (SqlCommand comm = new SqlCommand("select max(FlightBookingID) from dbo.FlightBookingDetails", FlyCon))
{
var result = comm.ExecuteScalar();
if (!Convert.IsDBNull(result))
Session["FBookingID"] = result;
}
DataSet is very complex class, and you shouldn't create it just to get one value from the database.
ds.Tables[0].Rows[0].Item["FlightBookingID"].toString();
You are getting String directly here
Try this.
Session["FBookingID"] = ds.Tables[0].Rows[0]["FlightBookingID"].ToString();
I think you should use Alias on your query :
SqlDataAdapter da = new SqlDataAdapter("select max(FlightBookingID) as FlightBookingID from dbo.FlightBookingDetails", FlyCon)
and so you can acces the column by name. Otherwise you can access it by column index :
Session["FBookingID"] = Convert.ToString(ds.Tables[0].Rows[0][0]);

Filling an arraylist from a datareader

I have a problem with how to fill an array list from a data reader
string queryDTL = " SELECT * FROM tbl1 ";
connection.Connect();
cmd = new OracleCommand(queryDTL, connection.getConnection());
dr_DTL = qcmd2.ExecuteReader();
ArrayList RecordsInfo = new ArrayList();
while (dr_DTL.Read())
{
RecordsInfo = dr_DTL["number"].ToString();
}
The problem is the datareader contain alot of info other than the number but I don't know how to put them in their correct position.
I am still a beginner in this sorry if it sounds stupid.
You can't put a String in an ArrayList. You have to add the string to the list.
Ex. :
ArrayList RecordsInfo = new ArrayList();
while (dr_DTL.Read())
{
RecordsInfo.Add(dr_DTL["number"].ToString());
}
If you want a list of String the best way is using List<String>.
Ex. :
List<String> RecordsInfo = new List<String>();
while (dr_DTL.Read())
{
RecordsInfo.Add(dr_DTL["number"].ToString());
}
I think you would be better off with a DataTable and an adapter:
SqlConnection Conn = new SqlConnection(MyConnectionString);
Conn.Open();
SqlDataAdapter Adapter = new SqlDataAdapter("Select * from Employees", Conn);
DataTable Employees = new DataTable();
Adapter.Fill(Employees);
GridView1.DataSource = Employees;
GridView1.DataBind();
Of course in your case, use the Oracle versions of the objects.
Hi you have to do RecordInfo.Add, currently you are reassigning the whole arraylist...
Also if you are retrieving too many columns, just query the columns you need, in your case number, not simply SELECT * ...

Categories

Resources