My SQL query is:
GridView1.DataSource = GetData();
GridView1.DataBind();
DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["OfficeConnection"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Consulting ", con))
{
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);
}
}
return dt;
}
I have a table with a few columns and what I am trying to achieve is to display the data in a GridView. At the moment the data is displayed in my GridView but I would like to replace text in the columns and then display in the gridview
So for example this is my table:
| DisplayName | $_License
+-------------+------------------------
| User 1 | TestLicense:License1 |
| User 2 | TestLicense:License2 |
So in my Gridview I would to display:
| Display Name | License Type |
+--------------+------------------------+
| User 1 | License1 |
| User 2 | License2 |
Note that theDisplay Name has a space and the $_License is changed to License Type and the row is changed from TestLicense:License1 to License1
Any help will be greatly appreciated.
Use this query:
"SELECT DisplayName 'Display Name', Replace($_License,'TestLicense:', '') 'License Type' Name FROM Consulting "
Modify your select query as per required result:
SELECT DisplayName AS 'Display Name' , RIGHT($_License, LEN($_License) - 11) AS 'License Type' FROM Consulting;
Related
I want to show some selected columns as my SQL column and the rest of the column should be pivot. My output should be: Please help me any idea ?
Pivot table
ID | Employee_ID | 01-sep-2019 | 02-sep-2019 | 03-sep-2019
───┼─────────────┼─────────────┼─────────────┼────────────
1 | 1001 | P | A | P
2 | 1002 | A | P | A
3 | 1003 | A | P | P
Original table
ID | Employee_ID |STATUS | Created_Date
───┼─────────────┼───────┼─────────────
1 | 1001 | P | 01-sep-2019
2 | 1002 | A | 02-sep-2019
3 | 1003 | P | 03-sep-2019
I use 2 `GridView to show data but it's applicable for all column that I don't need. Could you please help me?
private DataTable PivotTable(DataTable origTable) {
DataTable newTable = new DataTable();
DataRow dr = null;
//Add Columns to new Table
for (int i = 0; i <= origTable.Rows.Count; i++) {
newTable.Columns.Add(new DataColumn(origTable.Columns[i].ColumnName, typeof(String)));
}
//Execute the Pivot Method
for (int cols = 0; cols < origTable.Columns.Count; cols++) {
dr = newTable.NewRow();
for (int rows = 0; rows < origTable.Rows.Count; rows++) {
if (rows < origTable.Columns.Count) {
dr[0] = origTable.Columns[cols].ColumnName; // Add the Column Name in the first Column
dr[rows + 1] = origTable.Rows[rows][cols];
}
}
newTable.Rows.Add(dr); //add the DataRow to the new Table rows collection
}
return newTable;
}
private void BindGridView() {
string strConnString = ConfigurationManager.ConnectionStrings["SQLDBConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
try {
con.Open();
string sqlStatement = "SELECT Top(5)* FROM tbl_QC_Attandence";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, con);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
if (dt.Rows.Count > 0) {
//Bind the First GridView with the original data from the DataTable
grdorignal.DataSource = dt;
grdorignal.DataBind();
//Pivot the Original data from the DataTable by calling the
//method PivotTable and pass the dt as the parameter
DataTable pivotedTable = PivotTable(dt);
grdpivote.DataSource = pivotedTable;
grdpivote.DataBind();
}
} catch (System.Data.SqlClient.SqlException ex) {
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
} finally {
con.Close();
}
}
ORIGINAL TABLE
ID Employee_ID STATUS Created_Date
1 1001 P 01-sep-2019
2 1002 A 02-sep-2019
3 1003 P 03-sep-2019
PIVOT TABLE
ID Employee_ID 01-sep-2019 02-sep-2019 03-sep-2019
1 1001 P A P
2 1002 A P A
3 1003 A P P
I have create a dynamic query which can help you, but null can be replaced with 'A' in code side, try below one
DECLARE
#columns NVARCHAR(MAX) = '',
#sql NVARCHAR(MAX) = '',
#SelectColumnNames AS NVARCHAR(MAX);
SELECT
#columns += QUOTENAME([Created_Date]) + ','
FROM
Employee
ORDER BY
[Created_Date];
SET #columns = LEFT(#columns, LEN(#columns) - 1);
Select #SelectColumnNames = ISNULL(#SelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME([STATUS]) + ', 0) AS '
+ QUOTENAME([STATUS])
from (SELECT distinct [STATUS] from Employee) as Employees
print #SelectColumnNames
SET #sql =
N'Select * from(
select Created_Date,[STATUS],ID,Employee_ID
from Employee
)t
PIVOT(
MAX([STATUS])
FOR [Created_Date] IN ('+ #columns +')
) AS pivot_table
';
EXECUTE sp_executesql #sql;
I have a combobox that is filled with this db statement:
select ' ' as usr_entrada, null as No_Servicio union select usr_entrada, No_Servicio from Telemarketing where Id_Sucursal='cordoba'
Here the combobox is filled with a blank item before the true data, and the statement works perfectly, this is the result:
+--------------+-------------+
| usr_entrada | No_Servicio |
+--------------+-------------+
| | NULL |
+--------------+-------------+
| CAPTURA-TMK | No_Servicio |
+--------------+-------------+
| SUP | No_Servicio |
+--------------+-------------+
| TCA02TMK | No_Servicio |
+--------------+-------------+
| TCACONTABAUX | No_Servicio |
+--------------+-------------+
| TMKCBA01 | No_Servicio |
+--------------+-------------+`
The issue is that, when I fill the combobox, for some reason it erases the blank item, and I don't understand why. This is my method to fill the combobox:
void llenaUsuarios()
{
Conexion con = new Conexion();
DataTable dt=new DataTable();
using (con.getcon())
{
const string sql = "select ' ' as usr_entrada, null as no_servicio union select usr_entrada, No_Servicio from Telemarketing where Id_Sucursal=#Sucursal";
using(SqlCommand cmd=new SqlCommand(sql, con.getcon()))
{
SqlDataReader rd;
cmd.Parameters.AddWithValue("#Sucursal", cveSucursal);
rd = cmd.ExecuteReader();
if (rd.HasRows)
{
rd.Read();
dt.Load(rd);
comboBox1.DisplayMember = "usr_entrada";
comboBox1.ValueMember = "no_servicio";
comboBox1.DataSource = dt;
}
}
}
}
Can anyone tell me what am I doing wrong? The sql statement is not the problem, I have another combobox filled that way and it works just fine.
Thank you for your time :-)
So you want to insert a blank item in the combo box at index = 0, correct?
//rest of your code
comboBox1.DataSource = dt;
comboBox1.Items.Insert(0, new ListItem(" ", "-1")); //After filling the DataSource, insert an item in the Combobox at Index 0
What I have done here is to insert an item after the datasource is filled with the data from the DB. What happening in your code seems obvious to me. For more info on this, have a quick read. The article shows in Windows Forms but you'll get the idea in case you are on asp.net
Adding and Removing Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control
Last time I worked on these controls was almost a decade ago. I'm typing a sample here in SO, taking a reference from my old Source Control repo.
Common Variables
DataRow rw;
public DataSet ds = new DataSet();
public SqlDataReader dr;
public SqlCommand cmd = new SqlCommand();
public SqlDataAdapter adp = new SqlDataAdapter();
Using DataTable
//If DataSet contains the table already, remove it first
if (ds.Tables.Contains(tbl))
ds.Tables.Remove(tbl);
//Open connection here. Better with using
cmd.CommandText = "YOUR_SQL_QUERY_GOES_HERE";
adp.SelectCommand = cmd;
adp.Fill(ds, tbl);
//close the connection here
rw = ds.Tables[tbl].NewRow(); //Add a new row
rw[0] = "-1"; //Set it's value
rw[1] = "Itemtext"; //Set it's text
ds.Tables[tbl].Rows.InsertAt(rw, 0); //Insert this row in the DataTable(DT) at Index 0
comboBox1.DataSource = ds.Tables[tbl]; //Assign the DT in the DataSource of the combobox
comboBox1.DataTextField = "Default Text";
comboBox1.DataValueField = "Default Value";
comboBox1.DataBind();
Using DataReader
comboBox1.Items.Clear(); //Clear the dropdown first
//Open the connection, set SqlCommandType and Text
using (SqlDataReader reader = sqlcmd.ExecuteReader())
{
comboBox1.DataSource = reader; //Assign DataReader to the DataSource of the Combobox
comboBox1.DataValueField = "usr_entrada";
comboBox1.DataTextField = "no_servicio";
comboBox1.DataBind();
//Here you can insert a new item at Index 0 of the Combobox.
//For your case, keep the "Default Text" blank
comboBox1.Items.Insert(0, new ListItem("--Default Text--", "-1"));
}
//close the connection
Please note that the code is not optimized for production use and is only to give you more ideas! So do not penalize the answer because of the code quality. I have written it directly in SO and there might be some syntax errors!
I have an Access table which looks like this:
ID | col_1 | col_2 | col_n
1 | 12345 | ... | ...
1 | null | ... | ...
1 | null | ... | ...
2 | 67891 | ... | ...
What I want to accomplish is to get all col_1 with the ID 1 if there is at least one value in col_1 with that ID. So my result would be:
ID | col_1
1 | 12345
1 | null
1 | null
The following code gets me the all the values of ID and col_1 and stores them in a DataTable results0.
public void ConnectDB(string path, string query0, string query1)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Persist Security Info=False";
try
{
using (OleDbConnection conn = new OleDbConnection(connString))
{
DataTable results0 = new DataTable();
OleDbCommand cmd = new OleDbCommand(query0, conn);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results0);
}
}
catch (System.InvalidOperationException inv)
{
MessageBox.Show(inv.Message);
throw;
}
}
I wanted to use LINQ for this issue, since I don't want to loop through the rows and tried a few things without success. At first I thought something like this would give me the relevant values (which it does)
int id = 1;
for (int i = 0; i < 9; i++) // iterate through IDs and increment
{
IEnumerable<String> Ids =
results0
.AsEnumerable()
.Where(row => row.Field<Int32>("ID") == id)
.Select(row => row.Field<String>("FERI"));
id+=1;
}
but I'm not sure how to rephrase it in an if-statement. Something like "If ID = 1 and at least one value in col_1 get range of rows with ID = 1"
I hope this isn't too confusing.
Any help and suggestions are appreciated!
Update: I'm still having trouble getting the relevant rows. I tried using DataRow[], selecting all the rows with ID = 1 and iterating with foreach-loops but this doesn't seem really efficient. Can anyone help?
To get the list of records with ID==1 from the Database assuming database with name "DBName", we will have:
public DBName _dbContext = new DBName ();
and then using following LINQ query we will get result:
_dbContext.TableName.Where(u => u.ID == 1).Select(u => u.col_1 ).ToList();
Real easy.
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("col_1", typeof(int));
dt.Columns["col_1"].AllowDBNull = true;
dt.Rows.Add(new object[] { 1, 12345});
dt.Rows.Add(new object[] { 1, null});
dt.Rows.Add(new object[] { 1, null});
dt.Rows.Add(new object[] { 2, 67891});
int id = 1;
DataTable dt2 = dt.AsEnumerable().Where(x => x.Field<int>("ID") == id).CopyToDataTable();
I have one database and I want to get last value of column, and each time value will be updated after insertion
here is sample database,
ID | Customer_Name |new_Total | Total
--------------------------------------
1 | Mahesh | 100 | 200
2 | Mahesh | 400 | 600 (200+400)
3 | mahesh | 100 | 700 (600+100)
If i am getting you right you need to get last value of column i assume Total column.Here is you can read last value from database.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()))
{
SqlCommand cmd = new SqlCommand("select Top 1 Total from tablename order by total desc", con);
SqlDataReader rdr;
con.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int total;
int.TryParse(rdr["Total"].ToString(), out total);
}
}
You will get value in total variable and you can use it.
I am using C#(asp.net). I have two tables(data and details) in a same database.
Table "data"
id | chap | unit |
----------------
1| chap1|unit1 |
2| chap2|unit2 |
3| chap3|unit3 |
Table "details"
id| code| num |
----------------
1|abc |2 |
2|efg |3 |
3|hij |1 |
Now I want to fetch a value from "num" where code="efg" (in table "details"). And use the same value (3) to fetch data from table "data" by id. I am using this code.
OleDbConnection conn = new OleDbConnection(*** ...... *****);
OleDbCommand cmd;
OleDbDataReader reader;
String query = String.Format("select num from details where code="efg");
cmd = new OleDbCommand(query, conn);
reader = cmd.ExecuteReader();
int num = int.Parse(reader.GetValue(0).ToString());
query = String.Format("select chap from data where id={0}",num);
cmd = new OleDbCommand("select lesson from data where id=3", conn);
reader = cmd.ExecuteReader();
Label1.Text = reader.GetValue(0).ToString();
But it shows error. It shows "No data exists for the row/column."
You can use
SELECT d.chap, d.unit
FROM data d INNER JOIN details de
ON d.id = de.num
WHERE de.code = 'efg'
or
SELECT d.chap, d.unit
FROM data d INNER JOIN details de
ON d.id = de.num
AND de.code = 'efg'
More: if you're using SQL-Server, use SqlConnection in place of OleDbConnection.
More: don't format your query joining strings, numbers, dates and so on; use SqlParameter so you don't have to worry about types and formatting!!
Or you can use a subquery
SELECT * FROM data INNER JOIN
(SELECT num FROM details WHERE code='efg') det
ON data.id = det.num