asp.net multiple sqlcommands in one GridView - asp.net

I have problem to show multiple sql command in one GridView. Maybe I don't need two sqlcommands to show from two tables but I don't know how to do.
The first command is to get all employees that have vacation between two dates.
The second command I am using it to retrieve dates by ID. But I don't know how to Bind them both to one GridView to show as attached image. Thank you in advance.
What I get Now is
Albert 2016-03-16
Albert 2016-03-17
Albert 2016-03-18
Johanna 2016-03-17
Johanna 2016-03-18
Eric 2016-03-18
Instead of
Albert 2016-03-16, 2016-03-17, 2016-03-18
Johanna 2016-03-17, 2016-03-18
Eric 2016-03-18
I think I have to loop between two While statment and maybe with one sqlcommand?
My code is:
using (SqlConnection con = new SqlConnection(connection))
{
con.Open();
SqlCommand cmd = new SqlCommand(" SELECT distinct E.EmployeeId, E.FirstName
FROM Employee E INNER JOIN Vacation V ON E.EmployeeId = V.EmployeeId " +
" WHERE ((V.Dates >= #Start AND V.Dates <= #End) ) ", con);
cmd.Parameters.AddWithValue("#Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
cmd.Parameters.AddWithValue("#End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
Response.Write((dr[1]).ToString() + " "); // Cheack if retrivs Employeename
// Now By Id I want to get all dates belong to specifik employee
SqlCommand cmd2 = new SqlCommand(" SELECT V.Dates FROM Vacation V " +
" WHERE ((V.Dates >= #Start AND V.Dates <= #End) ) ", con);
cmd2.Parameters.AddWithValue("#Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
cmd2.Parameters.AddWithValue("#End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());
cmd2.Parameters.AddWithValue("#EmployeeId", Convert.ToInt32(dr[0]));
using (SqlDataReader dr2 = cmd2.ExecuteReader())
{
while (dr2.Read())
{
//Response.Write(Convert.ToDateTime(dr2[0]));
GridView7.DataSource = cmd2.ExecuteReader();
GridView7.DataBind();
}
}
Response.Write("<br/>");
}
}
con.close();
}
GridView7.DataSource = cmd.ExecuteReader();
GridView7.DataBind();

The FOR XML PATH syntax allows your query to group several values in a single one:
SELECT
E.EmployeeId,
E.FirstName,
REPLACE(STUFF((
SELECT
COALESCE('¶' + V.Dates, '')
FROM
Vacation V
WHERE
V.EmployeeId = E.EmployeeId AND V.Dates >= #Start AND V.Dates <= #End
FOR XML PATH('')), 1, 1, ''), '¶', ', ') AS VacationDates
FROM
Employee E
You can replace the ', ' separator by something else if you want.
Note: Sorry for the multipe edits. I am just not sure how you connect the employees, vacations and dates. This piece of code basically shows the idea for the FOR XML PATH syntax.

Related

Database value in label asp.net c#

I am trying to get value from database to be display in label. First i have to get the value of the dropdownlist and retrieved from database based on it. After that, I need to get the titlePromo column into my Label.
Currently i have the code out but i am not sure if it is the right one. There is no error but it displayed the membershipType column instead of the titlePromo.
ID titlePromo membershipType defaults
-- ---------- -------------- ------
1 Promo 1 Membership Promotion Y
2 Promo 2 Membership Renewal Y
3 Promo 3 Membership Grad Y
4 Promo 4 Membership Promotion N
5 Promo 5 Membership Promotion N
6 Promo 6 Membership Grad N
My codes that i have done so far:
string strConnectionString = ConfigurationManager.ConnectionStrings["FYPDB"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText2 = "select * FROM FYPDB.dbo.Promotions where membershipType = '%' + #membership + '%' AND defaults = 'Y'";
string ddlmembership = ((DropDownList)dvInsertPromotion.FindControl("ddlAddMembershiplist")).SelectedItem.ToString();
cmd.Parameters.Add("#membership", SqlDbType.NVarChar);
cmd.Parameters["#membership"].Value = ddlmembership;
DataSet da2 = dal.retrieveTitle(ddlmembership);
SqlCommand cmd2 = new SqlCommand(strCommandText2, myConnect);
((Label)pnlDefaultPopup.FindControl("Label13")).Visible = true;
((Label)pnlDefaultPopup.FindControl("Label13")).Text = da2.Tables[0].Rows[0]["titlePromo"].ToString();
html:
.cs
public DataSet retrieveTitle(String membership)
{
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("#membership", SqlDbType.NVarChar),
};
parameters[0].Value = membership;
DataSet ds = new DataSet();
ds = commons.ExecuteDataSet("Select * FROM Promotions WHERE (membershipType = '" + membership + "') AND defaults = 'Y' ");
return ds;
}
Before giving you my suggestion I would like to make some remarks to your existing code:
you should select only the titlePromo in your query, as you only need one field, and not the entire row (therefore you wouldn't need a dataset in the first place)
the naming of your function is not according to its scope, at it does not retrieve the title, but an entire entry in the promotions table.
in this structure "membershipType = '%' + #membership + '%'" the syntax is not correct. The wildcards are used together with the "like" keyword
Bellow, you can find my code sample of how would I implement it if I were you:
static void Main(string[] args)
{
using (SqlConnection PubsConn = new SqlConnection(yourConnectionString))
{
//code to retrieve membership
var membership = "Membership Promotion";
var title = retrieveTitle(PubsConn, membership);
//code to set up label
}
}
public static string retrieveTitle(SqlConnection conn, String membership)
{
conn.Open();
var title = string.Empty;
string strCommandText = "select top 1 titlePromo FROM Promotions where membershipType = #membership AND defaults = 'Y'";
SqlCommand commmand = new SqlCommand(strCommandText, conn);
commmand.Parameters.AddWithValue("#membership", membership);
try
{
using (SqlDataReader reader = commmand.ExecuteReader())
{
if (reader != null && reader.Read())
{
title = Convert.ToString(reader["titlePromo"]);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error while retrieving table: " + ex.Message);
}
conn.Close();
return title;
}
If you want to use wildcards and 'like', you can do it like this:
string strCommandText = "select top 1 titlePromo FROM membershipTest where membershipType like #membership AND defaults = 'Y'";
SqlCommand commmand = new SqlCommand(strCommandText, conn);
commmand.Parameters.AddWithValue("#membership", "%" + membership + "%");

ASP.NET , SqlDataReader and SqlCommand (There is already an open DataReader associated with this Command which must be closed first)

I'm getting this error:
There is already an open DataReader associated with this Command which must be closed first.
I don't know where is the problem. It's closed but still says it's open. Please help!
The first command is to get all employees that have vacation between two dates.
The second command I am using it to retrieve dates by ID.
Here is my code:
using (SqlConnection con = new SqlConnection(connection))
{
con.Open();
SqlCommand cmd = new SqlCommand(" SELECT distinct E.EmployeeId, E.FirstName FROM Employee E INNER JOIN Vacation V ON E.EmployeeId = V.EmployeeId " +
" WHERE ((V.Dates >= #Start AND V.Dates <= #End) ) ", con);
cmd.Parameters.AddWithValue("#Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
cmd.Parameters.AddWithValue("#End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
Response.Write((dr[1]).ToString() + " "); // Check if retrieves employee name
// Now by Id I want to get all dates belong to specific employee
SqlCommand cmd2 = new SqlCommand("SELECT V.Dates FROM Vacation V " +
" WHERE ((V.Dates >= #Start AND V.Dates <= #End) ) ", con);
cmd2.Parameters.AddWithValue("#Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
cmd2.Parameters.AddWithValue("#End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());
cmd2.Parameters.AddWithValue("#EmployeeId", Convert.ToInt32(dr[0]));
using (SqlDataReader dr2 = cmd2.ExecuteReader())
{
while (dr2.Read())
{
Response.Write(Convert.ToDateTime(dr2[0]));
}
}
Response.Write("<br/>");
}
GridView7.DataSource = cmd.ExecuteReader();
GridView7.DataBind();
}
con.close();
}
Add this to your connection string:
MultipleActiveResultSets=True

Need to insert a data row multiple times in the database

I have two data tables in sql. I need to insert data feom one table to another. My first data table Table1 contain data column Code,Model,Num,Qty and second table Table2 also contain the same. But I need to insert the data from table1 to table2 multiple times. If Qty in Table1 is 4 then, insert the data of
Table1 for 4 times according to the quantity.
protected void Button15_Click3(object sender, EventArgs e)
{
for (int i = 0; i < 4; i++)
{
String str1 = "insert into Table2(Code, Model, Num, Qty) select Code, Model, Num, Qty from Table1;";
SqlCommand xp1 = new SqlCommand(str1, con);
con.Open();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = xp1;
DataSet ds1 = new DataSet();
da1.Fill(ds1, "Code");
GridView1.DataSource = ds1;
con.Close();
}
}
}
In this program I give Number 4 manually, but I need to take it from my database qty. How can I put the SQL column name qty in the loop to insert the data at multiple time?
You can give a try like this:
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
int j = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for(j=0;j<=ds.Tables[0].Rows.Count;j++){
for (i = 0; i <= Convert.ToInt32(ds.Tables[0].Rows[j]["Qty"].ToString()); i++)
{
String str1 = "insert into Table2(Code, Model, Num, Qty)
select Code, Model, Num, Qty from Table1;";
SqlCommand xp1 = new SqlCommand(str1, con);
con.Open();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = xp1;
DataSet ds1 = new DataSet();
da1.Fill(ds1, "Code");
GridView1.DataSource = ds1;
con.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I hope it is clear now. !
As pointed out in the comments, duplicating rows isn't a good idea without a primary key on both the source and destination tables, as otherwise identification of rows will become problematic.
You haven't mentioned whether you want to copy just one row, multiple rows, or the whole table N times over, but assuming the latter, bulk IO jobs like this is better suited to doing the whole operation within the database server, in order to reduce the IO transferring data back and forth between your app and the database.
Assuming both tables are in the same database, here's a way you can do this with a row-duplicating recursive CTE. If you need to control the #CopyCount from C#, just bind it as an integer and execute it with SqlCommand.ExecuteNonQuery:
DECLARE #CopyCount INT = 10;
with cteRowGen AS
(
SELECT 1 AS RowNum
UNION ALL
SELECT RowNum + 1
FROM cteRowGen
WHERE RowNum < #CopyCount
)
insert into Table2(Code,Model,Num,Qty)
select Code,Model,Num,Qty
from table1 CROSS JOIN cteRowGen;
Like StuartLC pointed out, CTE is the way to go.
Here's a version that will read the QTY from your table1
It will also insert 1 for the Qty in Table2, and not 4
DECLARE #Cnt INT = (SELECT Qty FROM Table1);
WITH data AS (
SELECT 1 AS RowCnt
UNION ALL
SELECT RowCnt + 1
FROM data
WHERE RowCnt < #Cnt
)
INSERT INTO Table2
SELECT Code, Model, Num, 1 as Qty
FROM Table1 a
CROSS JOIN data

Search command using session variable asp.net

I have a name stored in a session variable called "name".
I have written the statement:
da = new SqlDataAdapter("Select empID from emp where empFirstName=' "+
Session["name"].ToString() + " '", connstring);
da.Fill(ds);
I have verified that the session variable is not empty. Yet i am not able to fetch the empID of the record that exists in the table. Is this statement correct?
You have spaces at the beginning and end of the string variable in SQL statement.
Try this, it should work:
da = new SqlDataAdapter("Select empID from emp where empFirstName='"+
Session["name"].ToString() + "'", connstring);
The problem was with the spaces over here:
' " + Session["name"].ToString() + " '"
^ ^
| |
that is why the values are suffixed and prefixed by a blank space.
You should try:
da = new SqlDataAdapter (
"Select empID from emp where empFirstName='" + Session["name"].ToString() + "'",
connstring);
da.Fill(ds);

Adding lines into chart control

I am struggling with SqlDataReader and ChartControl. I have added one line without any problem, but i want to add multiple of them and can't do that at all altought I was searching for that all day long.
What I have is table with some names of columns id, date, value1, value2, value3. I am getting them using SqlDataReader.
SqlConnection con4 = new
SqlConnection(ConfigurationManager.ConnectionStrings["przychodniaConnectionString1"].ConnectionString);
string cmdStr4 = "select badCisData, badCisSkurczowe, badCisRozkurczowe, badCisPuls from badanieCis where pacID='" +
Label3.Text + "' ORDER BY badCisData ASC";
SqlCommand getResults = new SqlCommand(cmdStr4, con4);
con4.Open();
SqlDataReader reader = getResults.ExecuteReader();
Then I am making my chart like that:
Chart2.Series["Series1"].Points.DataBindXY(reader, "badCisData",
reader, "badCisPuls");
Chart2.Series["Series2"].Points.DataBindXY(reader, "badCisData",
reader, "badCisSkurczowe");
And I have error on Series2. I would like to put date on x axis and on y axis (value1, value2 etc.)
using (SqlConnection con4 = new
SqlConnection(ConfigurationManager.ConnectionStrings["przychodniaConnectionString1"].ConnectionString))
{
string cmdStr4 = "select badCisData, badCisSkurczowe, badCisRozkurczowe, badCisPuls from badanieCis where pacID='" +
Label3.Text + "' ORDER BY badCisData ASC";
using (SqlCommand getResults = new SqlCommand(cmdStr4, con4))
{
con4.Open();
using (SqlDataReader reader = getResults.ExecuteReader())
{
if (reader.Read())
{
//Your code like reader["Column Name"]
}
}
}
}

Resources