Can anyone point me to where I make a mistake, I want to put a new sql query where I will read the data from the database and put them in my function, and in the end they will be displayed at the exit in the colon ("stunden") which currently appears on the first query SUM (zei.ZPZ_Std100) AS ZPZ_Std100
This looks like my entire code in the button
using (SqlConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString))
{
boAPI4.Login login = new boAPI4.Login();
string cS = login.GetConnectionString();
DataAccess dA = new DataAccess(cS);
int userID = dA.getLpeID(login.GetBoUserNr());
PRAESENZZEIT q = new PRAESENZZEIT();
q.ZPZ_LPE_ID = userID;
if (db.State == ConnectionState.Closed)
db.Open();
string query = "SELECT per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum, SUM (zei.ZPZ_Std100) AS ZPZ_Std100" +
" FROM DB.dbo.Z_PRAESENZZEIT zei INNER JOIN DB.dbo.A_PERSONAL per ON zei.ZPZ_LPE_ID = per.LPE_ID" +
$" WHERE zei.ZPZ_Datum BETWEEN '{dtFromDate.Value}' AND '{dtToDate.Value}' AND zei.ZPZ_LPE_ID='{userID.ToString()}' GROUP BY per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum ORDER BY zei.ZPZ_Datum, per.LPE_Nr;";
pRAESENZZEITBindingSource.DataSource = db.Query<PRAESENZZEIT>(query, commandType: CommandType.Text);
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
PRAESENZZEIT pra = new PRAESENZZEIT();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pra.ZPZ_Von = Convert.ToDateTime(dr["ZPZ_Von"]);
pra.ZPZ_Bis = Convert.ToDateTime(dr["ZPZ_bis"]);
listid.Add(pra);
}
dataGridView1.DataSource = listid;
con.Close();
DateTime kommen = DateTime.Now;
kommen = pra.ZPZ_Von;
if (pra.ZPZ_Von.TimeOfDay < new TimeSpan(8, 5, 0))
pra.ZPZ_Von = new DateTime(pra.ZPZ_Von.Year, pra.ZPZ_Von.Month, pra.ZPZ_Von.Day, 8, 0, 0);
DateTime gehen = DateTime.Now;
gehen = pra.ZPZ_Bis;
TimeSpan arbeitszeit = pra.ZPZ_Bis - pra.ZPZ_Von;
}
Currently, at the exit I get 0.
So, I need data that pass through the datetime variable
This is how it goes through the variables but returns the result as if it did not address base data, what's the problem? I understand if time [ZPZ_VON 07:45] that the exit should be 08:00..
SQL QUERY SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'
CODE:
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von, ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
while (dr.Read())
{
PRAESENZZEIT pra = new PRAESENZZEIT();
pra.ZPZ_Von = Convert.ToDateTime(dr["ZPZ_Von"]);
pra.ZPZ_Bis = Convert.ToDateTime(dr["ZPZ_bis"]);
listid.Add(pra);
DateTime kommen = DateTime.Now;
kommen = pra.ZPZ_Von;
if (pra.ZPZ_Von.TimeOfDay < new TimeSpan(8, 5, 0))
pra.ZPZ_Von = new DateTime(pra.ZPZ_Von.Year, pra.ZPZ_Von.Month, pra.ZPZ_Von.Day, 8, 0, 0);
DateTime gehen = DateTime.Now;
gehen = pra.ZPZ_Bis;
TimeSpan arbeitszeit = pra.ZPZ_Bis - pra.ZPZ_Von;
}
con.Close();
DATABASE QUERY RESULT:
You were initializing the pra class outside the while loop. Which doesn't add new record in the list listid every time read DataRow from DataReader.
Try this below code:
using (SqlConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString))
{
boAPI4.Login login = new boAPI4.Login();
string cS = login.GetConnectionString();
DataAccess dA = new DataAccess(cS);
int userID = dA.getLpeID(login.GetBoUserNr());
PRAESENZZEIT q = new PRAESENZZEIT();
q.ZPZ_LPE_ID = userID;
if (db.State == ConnectionState.Closed)
db.Open();
string query = "SELECT per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum, SUM (zei.ZPZ_Std100) AS ZPZ_Std100" +
" FROM DB.dbo.Z_PRAESENZZEIT zei INNER JOIN DB.dbo.A_PERSONAL per ON zei.ZPZ_LPE_ID = per.LPE_ID" +
$" WHERE zei.ZPZ_Datum BETWEEN '{dtFromDate.Value}' AND '{dtToDate.Value}' AND zei.ZPZ_LPE_ID='{userID.ToString()}' GROUP BY per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum ORDER BY zei.ZPZ_Datum, per.LPE_Nr;";
pRAESENZZEITBindingSource.DataSource = db.Query<PRAESENZZEIT>(query, commandType: CommandType.Text);
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
//PRAESENZZEIT pra = new PRAESENZZEIT(); //Needs to be inside the while loop.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
var listid = ConvertDataTable<PRAESENZZEIT>(dt);
dataGridView1.DataSource = listid;
con.Close();
}
private static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = newList<T>();
foreach (DataRowrow in dt.Rows)
{
Titem = GetItem<T>(row);
data.Add(item);
}
return data;
}
private static TGetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj =Activator.CreateInstance<T>();
foreach (DataColumncolumn in dr.Table.Columns)
{
foreach (PropertyInfopro in temp.GetProperties())
{
if (pro.Name == column.ColumnName)
pro.SetValue(obj,dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}
Related
I am trying to sort a datatable into a DataSet. I want to sort by the Status Column in "DESC". But I am not aware how to go about this. I have tried the suggested solutions online but I seem not to be doing something right. Here is what I have tried, albeit, I have commented out the sorting lines of the code as they do not work for me. How can I sort my table using the Status column in Desc?
[WebMethod(EnableSession = true)]
public List < TaskListClass > getTasks() {
var userId = Session["UserId"].ToString();
List < TaskListClass > objB = new List < TaskListClass > ();
try {
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ToString())) {
connection.Open();
DataSet Myds = new DataSet();
// Myds.Tables[0].DefaultView.Sort = "Status desc";
SqlDataAdapter sqldr = new SqlDataAdapter();
string ProcName = "getTasks";
SqlCommand cmd = new SqlCommand(ProcName, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#userId", SqlDbType.VarChar, 900).Value = userId;
sqldr.SelectCommand = cmd;
sqldr.Fill(Myds);
DataTable dt = Myds.Tables[0];
// DataTable dt = Myds.Tables[0].DefaultView.ToTable();
for (int i = 0; i < dt.Rows.Count; i++) {
objB.Add(new TaskListClass() {
Id = Convert.ToString(dt.Rows[i]["Id"]),
Subject = Convert.ToString(dt.Rows[i]["Subject"]),
Customer = Convert.ToString(dt.Rows[i]["Customer"]),
Sender = Convert.ToString(dt.Rows[i]["Sender"]),
Receiver = Convert.ToString(dt.Rows[i]["Receiver"]),
Priority = Convert.ToString(dt.Rows[i]["Priority"]),
StartDate = Convert.ToString(dt.Rows[i]["StartDate"]),
EndDate = Convert.ToString(dt.Rows[i]["EndDate"]),
Status = Convert.ToString(dt.Rows[i]["Status"]),
OnProgress = Convert.ToString(dt.Rows[i]["OnProgress"]),
});
}
}
} catch (Exception e) {
msg = e.ToString();
}
return objB;
}
Ok, a few things.
first up, a dataset is a collection of tables - "many tables" possible.
But you have ONE table, so why use a dataset? I see no need. Just use a single data table for this.
And this will reduce the code.
So, I suggest this, or close to this:
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ToString()))
{
using (var cmd = new SqlCommand("getTasks", connection))
{
connection.Open();
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
cmd.Parameters.Add("#userId", SqlDbType.VarChar).Value = userId;
dt.Load(cmd.ExecuteReader());
// now sort the datatable
dt.DefaultView.Sort = "Status DESC";
// now fill out our object with each row
foreach (DataRow OneRow in dt.Rows)
{
objB.Add(new TaskListClass()
{
Id = OneRow["Id"].ToString(),
Subject = OneRow["Subject"].ToString(),
Customer = OneRow["Customer"].ToString(),
Sender = OneRow["Sender"].ToString(),
Receiver = OneRow["Receiver"].ToString(),
Priority = OneRow["Priority"].ToString(),
StartDate = OneRow["StartDate"].ToString(),
EndDate = OneRow["EndDate"].ToString(),
Status = OneRow["Status"].ToString(),
OnProgress = OneRow["OnProgress"].ToString(),
}); ;
}
}
}
}
return objB;
The way the current code is written, you could add this after the for-loop:
objB = objB.OrderByDescending(t => t.Status).ToList();
Depending of the datatype of Status, it might be sorted alphabetically.
var dataRow = dt.AsEnumerable().OrderByDescending(x => x.Field<string>("Status")).ToList();
foreach (var item in dataRow)
{
//Enter your Code Here
}
Here dt is your datatable.
dataRow is a set of list.
After get the data list, you can asign it to your "objB".
I'm creating a leave calendar for employees, And for that I'm populating some data onto the calendar using dataset, but it takes too long to load the data.
I'm using multiple MySqlDataReader and connections to read the data from MySql table for each row of the calendar table. Maybe using multiple connections and readers might be the cause of slowing down but I'm not sure. The below is the code I use to populate the data.
class Sample
{
public DateTime Date { get; set; }
public string SlotAvailable { get; set; }
public string Pending { get; set; }
public string HeadCount { get; set; }
}
DateTime firstDate { get; set; }
DateTime lastDate { get; set; }
List<Sample> samples = new List<Sample>();
protected DataSet dsleaveplanner;
protected void FillLeaveplannerDataset()
{
cal2.VisibleDate = cal2.TodaysDate;
DateTime firstDate = new DateTime(cal2.VisibleDate.Year, cal2.VisibleDate.Month, 1).AddDays(-6);
DateTime lastDate = new DateTime(cal2.VisibleDate.Date.AddMonths(1).Year, cal2.VisibleDate.Date.AddMonths(1).Month, 1).AddDays(7);
dsleaveplanner = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (cal2.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = cal2.VisibleDate.Year + 1;
}
else
{
monthNumber = cal2.VisibleDate.Month + 1;
yearNumber = cal2.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate)
{
string site = lblsite.Text;
string skill = lblskill.Text;
string shift = lblshift.Text;
DataSet dsMonth = new DataSet();
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(MyConString);
string caldate = "Select * From setshrinkage Where date >= #firstDate And date <= #lastDate And site=#site And skill=#skill And shift=#shift Group By date";
MySqlCommand cmd = new MySqlCommand(caldate, con);
cmd.Parameters.AddWithValue("#firstDate", firstDate);
cmd.Parameters.AddWithValue("#lastDate", lastDate);
cmd.Parameters.AddWithValue("#site", site);
cmd.Parameters.AddWithValue("#skill", skill);
cmd.Parameters.AddWithValue("#shift", shift);
MySqlDataAdapter mysqlDataAdapter = new MySqlDataAdapter(cmd);
try
{
mysqlDataAdapter.Fill(dsMonth);
con.Close();
}
catch { }
return dsMonth;
}
public void caldisp(DayRenderEventArgs e)
{
Environment.NewLine.ToString();
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p></p>Slot available:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().SlotAvailable.ToString()));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().Pending.ToString()));
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
//e.Day.IsSelectable = false;
if (dsleaveplanner != null)
{
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
var hcount = (dr["headCount"].ToString());
Int32 hcount1 = Convert.ToInt32(hcount);
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection conn = new MySqlConnection(MyConString);
string cntdate = "SELECT COUNT(date) FROM approved WHERE date = #date And site=#site And skill=#skill And shift=#shift And status=#status";
string cntdate2 = "SELECT COUNT(date) FROM approved WHERE date = #date And site=#site And skill=#skill And shift=#shift And status=#status";
MySqlCommand cmd2 = new MySqlCommand(cntdate, conn);
MySqlCommand cmd3 = new MySqlCommand(cntdate2, conn);
cmd2.Parameters.AddWithValue("#date", nextDate);
cmd2.Parameters.AddWithValue("#site", lblsite.Text);
cmd2.Parameters.AddWithValue("#skill", lblskill.Text);
cmd2.Parameters.AddWithValue("#shift", lblshift.Text);
cmd2.Parameters.AddWithValue("#status", "auto-approved");
cmd3.Parameters.AddWithValue("#date", nextDate);
cmd3.Parameters.AddWithValue("#site", lblsite.Text);
cmd3.Parameters.AddWithValue("#skill", lblskill.Text);
cmd3.Parameters.AddWithValue("#shift", lblshift.Text);
cmd3.Parameters.AddWithValue("#status", "pending");
string chklog = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd1 = new MySqlCommand(chklog, conn);
cmd1.Parameters.AddWithValue("#date", nextDate);
cmd1.Parameters.AddWithValue("#login", Label1.Text);
cmd1.Parameters.AddWithValue("#stat", "auto-approved");
conn.Open();
string count = cmd2.ExecuteScalar().ToString();
string count2 = cmd3.ExecuteScalar().ToString();
var slot2 = Convert.ToInt32(count);
Int32 slot3 = hcount1 - slot2;
string slot4 = slot3.ToString();
MySqlDataReader dr1 = cmd1.ExecuteReader();
MySqlConnection con = new MySqlConnection(MyConString);
string chklog1 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd4 = new MySqlCommand(chklog1, con);
cmd4.Parameters.AddWithValue("#date", nextDate);
cmd4.Parameters.AddWithValue("#login", Label1.Text);
cmd4.Parameters.AddWithValue("#stat", "pending");
con.Open();
MySqlDataReader dr2 = cmd4.ExecuteReader();
MySqlConnection con2 = new MySqlConnection(MyConString);
string chklog2 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd5 = new MySqlCommand(chklog2, con2);
cmd5.Parameters.AddWithValue("#date", nextDate);
cmd5.Parameters.AddWithValue("#login", Label1.Text);
cmd5.Parameters.AddWithValue("#stat", "rejected");
con2.Open();
MySqlDataReader dr3 = cmd5.ExecuteReader();
MySqlConnection con3 = new MySqlConnection(MyConString);
string chklog3 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd6 = new MySqlCommand(chklog3, con3);
cmd6.Parameters.AddWithValue("#date", nextDate);
cmd6.Parameters.AddWithValue("#login", Label1.Text);
cmd6.Parameters.AddWithValue("#stat", "agent-withdrawn");
con3.Open();
MySqlDataReader dr4= cmd6.ExecuteReader();
if (nextDate == e.Day.Date)
{
if (dr1.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.LightGreen;
}
else if (dr2.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.Gold;
}
else if (dr3.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.Tomato;
}
else if (dr4.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.DarkTurquoise;
}
}
conn.Close();
con.Close();
con2.Close();
con3.Close();
samples.Add(new Sample { Date = nextDate, SlotAvailable = slot4, Pending = count2 });
}
if (samples.Any(x => x.Date == e.Day.Date))
{
string weekoff = lblweekoff.Text;
List<string> offday = (lblweekoff.Text).Split(',').ToList();
if (offday.Contains(e.Day.Date.ToString("ddd")))
{
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Week-Off </p>"));
}
else
{
caldisp(e);
}
}
else
{
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Target not set! </p>"));
}
}
}
How can I make this process faster? Any help is appreciated, Thanks in advance!
You have 6 SQL queries into foreach statement, if you have 10 rows in dsleaveplanner the program will execute 60 SQL queries. this number of SQL queries will have a negative impact on performance.
try to retrieve all data before your foreach statement and stock data into lists (memory) then use it within your foreach
i'm trying to get multiple values from database in return, i write a code and it return me only one value but i want all values in return. i didn't know how to solve it because i'm beginner in c#. here is code
string CommandText = "SELECT * FROM SV WHERE [SVCode]=#id";
using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
{
cmd.Parameters.AddWithValue("#id", sve.SVID);
conn.Open();
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
sve.SVName = dr["SVName"].ToString();
sve.SVCity = dr["SVCity"].ToString();
sve.SVState = dr["SVState"].ToString();
sve.SVEmail = dr["SVEmail"].ToString();
sve.SVWebsite = dr["SVWebsite"].ToString();
sve.SVAddress = dr["SVAddress"].ToString();
sve.SVNote = dr["SVNote"].ToString();
}
return sve.SVName; //how to return SVCity,SVState,SVEmail,SVWebsite,SVAddress,SVNote
}
private string SVCB(){
SVE sve = new SVE();
sve.SVID = MSVD_vendorcode.SelectedItem.ToString();
sve.SVName = MSVD_vendorname.Text;
sve.SVCity = MSVD_vendorcity.Text;
sve.SVState = MSVD_vendorstate.Text;
sve.SVEmail = MSVD_vendoremail.Text;
sve.SVWebsite = MSVD_vendorwebsite.Text;
sve.SVAddress = MSVD_vendoraddress.Text;
sve.SVNote = MSVD_vendornote.Text;
SVSCB sv = new SVSCB();
return sv.SVCBSI(sve);}
private void SVcode_SelectedIndexChanged(object sender, EventArgs e)
{
MSVname.Text = SVCB();
MSVcity.Text = SVCB();
MSVstate.Text = SVCB();
MSVemail.Text = SVCB();
MSVwebsite.Text = SVCB();
MSVaddress.Text = SVCB();
MSVnote.Text = SVCB();
}
this code working but show only one value of SVName in every textbox.
Update!!
public static string SV_CBSI(SVE sve)
{
using (SQLiteConnection conn = new SQLiteConnection(DatabaseConnection.ConnectionString()))
{
string CommandText = "SELECT * FROM SV WHERE [SVCode]=#id";
using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
{
cmd.Parameters.AddWithValue("#id", sve.SVID);
conn.Open();
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
sve.SVName = dr["SVName"].ToString();
sve.SVCity = dr["SVCity"].ToString();
sve.SVState = dr["SVState"].ToString();
sve.SVEmail = dr["SVEmail"].ToString();
sve.SVWebsite = dr["SVWebsite"].ToString();
sve.SVAddress = dr["SVAddress"].ToString();
sve.SVNote = dr["SVNote"].ToString();
}
return sve.SVName; //how to return SVCity,SVState,SVEmail,SVWebsite,SVAddress,SVNote
}
}
}
public static string SVCBSI(SVE sve)
{
return SVWCB.SV_CBSI(sve);
}
here is complete code
You need to have a method that return the whole SVE retrieved from database given a particular SVCode.
Notice that I suppose that SVCode is an integer. If not change the input type for this method accordingly
public SVE SV_CBSI(int id)
{
SVE localSve = new SVE();
string CommandText = "SELECT * FROM SV WHERE [SVCode]=#id";
using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
{
cmd.Parameters.AddWithValue("#id", id);
conn.Open();
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
if(dt.Rows.Count > 0)
{
localSve.SVName = dr["SVName"].ToString();
localSve.SVCity = dr["SVCity"].ToString();
localSve.SVState = dr["SVState"].ToString();
localSve.SVEmail = dr["SVEmail"].ToString();
localSve.SVWebsite = dr["SVWebsite"].ToString();
localSve.SVAddress = dr["SVAddress"].ToString();
localSve.SVNote = dr["SVNote"].ToString();
}
return localSve;
}
}
Now you can call this method and get back the reference to an SVE instance filled with your data.
private void SVcode_SelectedIndexChanged(object sender, EventArgs e)
{
SVE currentSVE = SV_CBSI(Convert.ToInt32(SVCode.SelectedItem))
MSVname.Text = currentSVE.SVName;
MSVcity.Text = currentSVE.SVCity;
MSVstate.Text = currentSVE.State;
MSVemail.Text = currentSVE.SVEmail;
MSVwebsite.Text = currentSVE.SVWebsite;
MSVaddress.Text = currentSVE.SVAddress;
MSVnote.Text = currentSVE.SVNote;
}
May be you need to return an array (or a List) of strings?
I am returning a dataRow from SQL server that contains appointments: Subject, Starting date, Ending date and Channel id.
I need to loop on each item of the dataRow to be able to group the items of a specific channel id in a separately to be able to add them to ultraGanttView.
The following code is working correctly to bind the data to a UltreMonthViewSingle.
So what i need to be able to bind the data in a ganttView is to group them by project which is the channel id in my case.
private void FillCalendar()
{
string query = #"select rs.[Planned Date in] as pdin,rs.[Planned Date out] as pdout, CONCAT(cn.Name,' ',ps.[First Name],' ',ps.[Last Name]) as subj, cn.[ID]
from [dbo].[Reservations] rs
inner join [dbo].[Person] ps on rs.[Person ID] = ps.ID
inner join [dbo].[Channel] cn on rs.[Channel ID] = cn.ID";
SqlConnection conn = new SqlConnection(Utilities.ConnectionString);
conn.Open();
//return reservations datatable
DataTable table = new DataTable();
SqlDataAdapter adp2 = new SqlDataAdapter(query, conn);
adp2.Fill(table);
//bind appointments
Appointment appointment;
DateTime dateIn, dateOut;
String subj;
foreach (DataRow dataRow in table.Rows)
{
dateIn = DateTime.Parse(dataRow["pdin"].ToString());
dateOut = DateTime.Parse(dataRow["pdout"].ToString());
dateIn.ToString("dd-MMMM-yyyy");
subj = dataRow["subj"].ToString();
appointment = this.ultraCalendarInfo1.Appointments.Add(dateIn, dateOut, subj);
}
}
What should i add to the loop so it can work?
This is a documentation how to bind data in ganttView GanttView Binding
Thank you
This is what i have done and it is working.
private void BindGantt()
{
this.ultraGanttView1.CalendarInfo = this.ultraCalendarInfo1;
string query = "select rs.[Channel ID],c.Name from[dbo].[Reservations] rs inner join[dbo].[Channel] c on rs.[Channel ID] = c.ID group by rs.[Channel ID],c.Name";
DataTable dt = new DataTable();
DataTable dc = new DataTable();
SqlConnection conn = new SqlConnection(Utilities.ConnectionString);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DateTime dateFrom;
TimeSpan duration;
string subject;
int id;
//get the channels' id that have reservations
for (int j = 0; j < dt.Rows.Count; j++)
{
id = Convert.ToInt32(dt.Rows[j].ItemArray[0].ToString());
dc = GetChannelsReservations(id);
//get the info of all the reservations for a channel
ultraCalendarInfo1.Tasks.Add(DateTime.Now, TimeSpan.FromDays(0), dt.Rows[j].ItemArray[1].ToString());
for (int i = 0; i < dc.Rows.Count; i++)
{
dateFrom = Convert.ToDateTime(dc.Rows[i].ItemArray[0]);
TimeSpan.TryParse(dc.Rows[i].ItemArray[1].ToString(),out duration);
subject = dc.Rows[i].ItemArray[2].ToString();
ultraCalendarInfo1.Tasks[j].Tasks.Add(dateFrom, duration, subject);
}
}
}
private DataTable GetChannelsReservations(int id) {
string query = #"select rs.[Planned Date in],DATEDIFF(DAY, rs.[Planned Date in],rs.[Planned Date out]) as TimeSpan,c.Name+' '+p.[First Name]+' '+p.[Last Name],c.Name
from[dbo].[Reservations] rs
inner join[dbo].[Channel] c on rs.[Channel ID] = c.ID
inner join[dbo].[Person] p on rs.[Person ID] = p.ID
where rs.[Channel ID] ="+id;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(Utilities.ConnectionString);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
how are you ?
i have a problem loading data from DB (connexion string is good, since I can insert data into DB) into my data Table.
my query also works fine, when execute in Sql management studio I received 15 records... so after some lonely search and tries, I come to you.
Here is the code of my function supposed to get Value from DB.
The code stops at 'dt.Load(sqlCommand.ExecuteReader());' , where it seems to search, but i obtain after some seconds , a timeout exeption. And I as I
public List<string> GetConfigurationValues(string configurationKey, int? idBusinessUnit, int? idDomain)
{
string conn = ConnectionStringHelper.GetIdentityConnectionString();
List<string> conf = new List<string>();
using (SqlConnection dbConnection = new SqlConnection(conn))
{
dbConnection.Open();
SqlCommand sqlCommand = new SqlCommand(#"
SELECT Value
FROM ConfigurationValue cv
INNER JOIN ConfigurationFilter cf ON cv.idConfigurationValue = cf.idConfigurationValue
INNER JOIN ConfigurationKey ck ON ck.idConfigurationKey = cf.idConfigurationKey
WHERE ck.KeyName = #ConfigurationKey
AND((cf.idDomain = #idDomain) OR(cf.idDomain IS NULL))
AND((cf.idBusinessUnit = #idBusinessUnit) OR(cf.idBusinessUnit IS NULL))", dbConnection);
sqlCommand.CommandType = System.Data.CommandType.Text;
sqlCommand.Parameters.Add(new SqlParameter("#ConfigurationKey", "PORTAL_THEME"));
if (idBusinessUnit == null)
sqlCommand.Parameters.Add(new SqlParameter("#idBusinessUnit", null)); //DBNull.Value
else
sqlCommand.Parameters.Add(new SqlParameter("#idBusinessUnit", null));
if (idDomain == null)
sqlCommand.Parameters.Add(new SqlParameter("#idDomain", null));// DBNull.Value
else
sqlCommand.Parameters.Add(new SqlParameter("#idDomain", 281));
DataTable dt = new DataTable();
dt.Load(sqlCommand.ExecuteReader());
//dbConnection.Close();
if (dt != null)
if (dt.Rows.Count > 0)
foreach (DataRow dr in dt.Rows)
conf.Add(Convert.ToString(dr["Value"]));
}
return conf;
}
Try this:
SqlCommand sqlCommand = new SqlCommand(#"
SELECT Value
FROM ConfigurationValue cv
INNER JOIN ConfigurationFilter cf ON cv.idConfigurationValue = cf.idConfigurationValue
INNER JOIN ConfigurationKey ck ON ck.idConfigurationKey = cf.idConfigurationKey
WHERE ck.KeyName = #ConfigurationKey
AND((cf.idDomain = #idDomain) OR(cf.idDomain IS NULL))
AND((cf.idBusinessUnit = #idBusinessUnit) OR(cf.idBusinessUnit IS NULL))", dbConnection);
sqlCommand .CommandTimeout = 500;
thank you, for your kind attention.I solved it this morning. it was a probleme in the way I excecuted the load of the dataTable. Instead of a dataTable I am using now a DataReader. I precise, that if we use the dataReader, we get the right error message (it s a bonus.) So here is the part of the code I changed (for thoose who want to know) :
public List<string> GetConfigurationValues(string configurationKey, int? idBusinessUnit, int? idDomain)
{
string conn = ConnectionStringHelper.GetIdentityConnectionString();
string valueRes;
int idConfigurationKey = 0;
if (configurationKey == "PORTAL_THEME") { idConfigurationKey = 3; }
else if (configurationKey == "LOGO_THEME") { idConfigurationKey = 4; }
List<string> conf = new List<string>();
DataTable dt = new DataTable();
using (SqlConnection dbConnection = new SqlConnection(conn))
{
dbConnection.Open();
SqlCommand command = dbConnection.CreateCommand();
SqlTransaction transaction;
transaction = dbConnection.BeginTransaction("SampleTransaction");
command.Connection = dbConnection;
command.Transaction = transaction;
try
{
command.CommandText = #"
SELECT Value
FROM ConfigurationValue cv
INNER JOIN ConfigurationFilter cf ON cv.idConfigurationValue = cf.idConfigurationValue
INNER JOIN ConfigurationKey ck ON ck.idConfigurationKey = cf.idConfigurationKey
WHERE cf.idConfigurationKey = #ConfigurationKey
AND((cf.idDomain = #idDomain) OR(cf.idDomain IS NULL))
AND((cf.idBusinessUnit = #idBusinessUnit) OR(cf.idBusinessUnit IS NULL))";
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add(new SqlParameter("#ConfigurationKey", idConfigurationKey));
if (idBusinessUnit == null)
command.Parameters.Add(new SqlParameter("#idBusinessUnit", DBNull.Value)); //DBNull.Value
else
command.Parameters.Add(new SqlParameter("#idBusinessUnit", idBusinessUnit));
if (idDomain == null)
command.Parameters.Add(new SqlParameter("#idDomain", null));// DBNull.Value
else
command.Parameters.Add(new SqlParameter("#idDomain", idDomain));
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
string theme = reader["Value"].ToString();
conf.Add(theme);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
}
}
return conf;
}