Change Column name(s) in DataGridView - c#

I use the following code to change the Column Name but unfortunately it won't let me do that. Please help me to solve this problem:
DateTime dt = DateTime.Now;
string s = dt.DayOfWeek.ToString();
for (int i = 0; i < 10; i++)
{
dataGridView1.Columns.Add(string.Format("col{0}", i), s);
}
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
int c = dataGridView1.CurrentCell.ColumnIndex;
string str = dataGridView1.Columns[c].HeaderText;
if (str == "Wednesday")
{
str = "fifth day of week";
}
}
Also is there any way so that I can get all day of week after each other between specific datetimes.
Any help will be appreciated

You need to set DataGridView.Column[index].HeaderText:
DateTime dt = DateTime.Now;
string s = dt.DayOfWeek.ToString();
for (int i = 0; i < 10; i++)
{
dataGridView1.Columns.Add(string.Format("col{0}", i), s);
}
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
string str = dataGridView1.Columns[i].HeaderText;
if (str == "Wednesday")
{
dataGridView1.Columns[i].HeaderText = "fifth day of week";
}
}

Add this line to Datagridview DataBindingComplete event handler
this.dataGridView1.Columns["your database column name"].HeaderText = " preferred name";

The below code will get all days of week after each other between specific datetimes and print the names of the days as column headers:
DateTime dtStart = new DateTime(2012, 11, 1);
DateTime dtEnd = new DateTime(2012, 11, 7);
for (int i = 0; i < dtEnd.Subtract(dtStart).Days; i++)
{
TimeSpan counter = new TimeSpan(i, 0, 0, 0);
dataGridView1.Columns.Add(string.Format("col{0}", i), (dtStart + counter).DayOfWeek.ToString());
}

Related

Why List is not filled with n number of records and x number of dates, 2 differen records per date, until all dates are used? C#

int dateOffset = 0;
DateTimeOffset currentDate = DateTimeOffset.Now;
do
{
int sameDayCount = 0;
do
{
for (int record = 0; record < List.Count; record++)
{
Client client = new Client();
client.Name = List[record].Name;
client.Date = currentDate.AddDays(dateOffset);
List2.Add(client);
sameDayCount += 1;
}
} while (sameDayCount < 2);
dateOffset += 1;
} while (dateOffset < 30);
The above is the code I wrote thanks to my modest knowledge about and experience with the C# language.
As you may expect it does not work as expected.
I need to populate the List2 with data from the List and additional element -DateTime.
Basically I want to schedule the names of clients for 30 days, two per day.
In the code i wrote I was hoping that do{} while (sameDayCount < 2); will work, but the sameDayCount += 1; is inside the for loop and do{} while actually waits for the for loop to finish (when it reaches record == List.Count). Anyway, the for loop will start over from record = 0 and I need it to go on from the last point it was left out when reached 2 records per day.
Any idea how I could resolve the problem?
So there are:
a List with finite number of records (Client's names)
30 days to be asssigned along with records
there must be two different records for each date
list with records must be re-read from the place it was left off
when the list is fully iterated(b=List.Count), it starts over again from b=0
the whole loop ends when 30th day is reached.
in few words, seen that my question is not clear at all.
Lets say first list contains 5 clients(the number may vary).
I want to populate second list with those 5 clients + 7 days.
I want the second list to become like:
day1 - client1, client2
day2 - client3, client4
day3 - client5, client1
day4 - client2, client3
day5 - client4, client5
day6 - client1, client2
day7 - client3, client4
You can do it with one for-loop only by stepping by 2
DateTime currentDate = DateTime.Now.Date;
for (int i = 0; i < List.Count && i < 60; i += 2) {
AddClient(i, currentDate);
if (i + 1 < List.Count) {
AddClient(i + 1, currentDate);
}
currentDate = currentDate.AddDays(1);
}
void AddClient(int clientIndex, DateTime dateTime)
{
var client = new Client {
Name = List[clientIndex].Name,
Date = dateTime
};
List2.Add(client);
}
You don't need a loop for the 30 days. Just loop until the clients run out (i < List.Count) or you have scheduled 60 clients, i.e., until you have reached 30 days. In case the number of clients is odd, i + 1 < List.Count makes sure that you don't exceed the list.
If you want to be more flexible with the count of clients per day, use 2 loops. One which loops through the source list in steps of ClientsPerDay and one which loops the ClientsPerDay:
const int ClientsPerDay = 2;
DateTime currentDate = DateTime.Now.Date;
for (int i = 0; i < List.Count && i < ClientsPerDay * 30; i += ClientsPerDay) {
for (int j = 0; j < ClientsPerDay; j++) {
int clientIndex = i + j;
if (clientIndex < List.Count) {
var client = new Client {
Name = List[clientIndex].Name,
Date = currentDate
};
List2.Add(client);
}
}
currentDate = currentDate.AddDays(1);
}
As an alternative you could calculate the loop count in advance with
int clientCount = Math.Min(List.Count, ClientsPerDay * 30);
for (int i = 0; i < clientCount; i += ClientsPerDay) {
...
}
Starting over
You have changed the question in the meantime. If you want start over with the clients if the number of days is not reached but the clients run out, you can use the modulo operator (%) to make the indexes start over.
const int ClientsPerDay = 2, NumDays = 30;
DateTime date = DateTime.Now.Date;
for (int i = 0; i < ClientsPerDay * NumDays; i += ClientsPerDay) {
for (int j = 0; j < ClientsPerDay; j++) {
int clientIndex = (i + j) % List.Count; // clientIndex = [0 .. List.Count - 1]
var client = new Client {
Name = List[clientIndex].Name,
Date = date
};
List2.Add(client);
}
date = date.AddDays(1);
}
See also: Circular array on GeeksforGeeks.
Well, I think I understand the question - so here is what I suggest you do:
First, loop over the Client's names only once.
Inside that loop, nest a second loop, counting from 0 to 59.
In that loop, add the clients to the target list, adding the inner loop counter % 30 days to the current datetime value:
// meaningful names - i is kinda "defacto standard" as a for loop counter
for (int i = 0; i < List.Count; i++)
{
// using j for nesting loops is also kinda "defacto standard"
for(int j = 0; j < 60; j++)
{
// you already know it's a client, use var!
var client = new Client();
client.Name = List[record].Name;
client.Date = currentDate.AddDays(j % 30);
List2.Add(client);
}
}
Of course, there are more advanced solutions for this kind of thing like using linq - but I'm not sure I'm comfortable suggesting linq to a c# beginner - I think it's better to start with the basics and work your way up to advanced stuff.
as Olivier Jacot-Descombes suggested:
const int ClientsPerDay = 2;
DateTime currentDate = DateTime.Now.Date;
for (int i = 0; i < List.Count && i < ClientsPerDay * 30; i += ClientsPerDay) {
for (int j = 0; j < ClientsPerDay; j++) {
int clientIndex = i + j;
if (clientIndex < List.Count) {
var client = new Client {
Name = List[clientIndex].Name,
Date = currentDate
};
List2.Add(client);
}
}
currentDate = currentDate.AddDays(1);
}
But this goes until the List.Count is reached. So it populates the list only until the clients are all used.
Instead, I am looking for a solution that will loop the same Clients until 30 day limit is reached.
Something like this:
do
{
const int ClientsPerDay = 2;
DateTime currentDate = DateTime.Now.Date;
for (int i = 0; i < List.Count && i < ClientsPerDay * 30; i += ClientsPerDay) {
for (int j = 0; j < ClientsPerDay; j++) {
int clientIndex = i + j;
if (clientIndex < List.Count) {
var client = new Client {
Name = List[clientIndex].Name,
Date = currentDate
};
List2.Add(client);
}
}
currentDate = currentDate.AddDays(1);
}
} while (currentDate < currentdate.AddDays(30));
But my Do simply repeats the job instead of going on with dates.
Something like this, I guess? All dates in UTC - it's easier to work with canonical datetimes rather than using those crappy looking offsets. You can always convert them to locale when you need to show them in terminal, so there is no reason to work with them up until final point.
public static void Main(string[] args)
{
var currentDate = DateTime.UtcNow;
var daysInMonth = DateTime.DaysInMonth;
var repeats = 2;
for(var i = 0; i < daysInMonth;i++)
{
foreach(var item in List)
{
for(var r = 0; r < repeats;r++)
{
var client = new Client
{
Name = item.Name,
Date = currentDate.AddDays(i)
};
List2.Add(client);
}
}
}
}
PS: Question is really bad, I didn't understand a thing.

How to edit a asp.net chart X Axis label and only show date and not time

How do I remove the time from the X Axis in my chart.
My sql returns date only but my code adds the time again.
I have tried:
Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "##-##-##";
But no luck.
My current code:
Chart1.Visible = ddlChart.SelectedValue != "";
string query = string.Format(stest);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
int[] y = new int[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
Chart1.Series[0].Points.DataBindXY(x, y);
Chart1.Series[0].ChartType = SeriesChartType.Bar;
Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
Chart1.Legends[0].Enabled = true;
WORKING CODE - Thanks jstreet
Chart1.Visible = ddlChart.SelectedValue != "";
string query = string.Format(stest);
DataTable dt = GetData(query);
DateTime[] x = new DateTime [dt.Rows.Count];
int[] y = new int[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = Convert.ToDateTime(dt.Rows[i][0]);
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
Chart1.Series[0].Points.DataBindXY(x, y);
Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yyyy";
Chart1.Series[0].ChartType = SeriesChartType.Bar;
Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
Chart1.Legends[0].Enabled = true;
In a Bar chart (as opposed to a Column chart), the vertical axis is the AxisX, not AxisY. Also, avoid assigning a string to your AxisX. It is not necessary at all and may cause problems.
Use this:
Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yyyy";
or this:
Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yy";
EDIT:
Here's some sample code:
protected void Page_Load(object sender, EventArgs e)
{
DateTime[] x = new DateTime[3];
int[] y = new int[3];
for (int i = 0; i < 3; i++)
{
x[i] = DateTime.Now.AddDays(i);
y[i] = 10 * (i + 1);
}
Chart1.Series[0].Points.DataBindXY(x, y);
Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yy";
}
The following below should work
for (int i=0; i < dt.Rows.Count; i++)
{
DataRow row = dt.Rows[i];
x[i] = DateTime.ParseExact(row[0].ToString(), 'MM-dd-yy', CultureInfo.InvariantCulture);
y[i] = Convert.ToInt32(row[1]);
}

CSV to SQL - Add 1 day to a Date in a datacolumn

I am trying to add 1 day to all dates that are in a certain datacolumn ['RecordAddedDate']
csvData.Columns.AddRange(new DataColumn[3] {
new DataColumn("Manufacturer", typeof(string)),
new DataColumn("SupplierCode", typeof(string)),
new DataColumn("RecordAddedDate", typeof(DateTime))});
At the moment the moment I have this working:
for (int rowIndex = 0; rowIndex < csvData.Rows.Count; rowIndex++)
{
DateTime dt2 = DateTime.Parse(fieldData[2]);
var newDate = dt2.AddDays(1);
csvData.Rows[rowIndex][2] = newDate;
}
But it only adds 1 day to the first row read from the csv and doesn't add for the rest.
Any Help?
Here is the while loop which reads the data from the csv and adds the data
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
Console.WriteLine(fieldData[i]);
if (fieldData[i] == "")
{
fieldData[i] = null;
}
for (int rowIndex = 0; rowIndex < csvData.Rows.Count; rowIndex++)
{
DateTime dt2 = csvData.Rows[rowIndex].Field<DateTime>(2);
DateTime newDate = dt2.AddDays(1);
csvData.Rows[rowIndex][2] = newDate;
}
}
csvData.Rows.Add(fieldData);
Console.WriteLine("Rows count:" + csvData.Rows.Count);
}
}
return csvData;
What is fieldData[2]? You are always using this in the loop, so no wonder that you always get the same DateTime. If the table is already filled and you want to update a value use csvData.Rows[rowIndex][2] = csvData.Rows[rowIndex].Field<DateTime>(2).AddDays(1);
for (int rowIndex = 0; rowIndex < csvData.Rows.Count; rowIndex++)
{
DateTime dt2 = csvData.Rows[rowIndex].Field<DateTime>(2);
DateTime newDate = dt2.AddDays(1);
csvData.Rows[rowIndex][2] = newDate;
}

How to iterate date in for loop?

I have some values.
DateTime date=04/03/2015(date)
Total Woring days=6 (total)
Rotation Days=2 (rotationday)
Shift Group=S1(this group contain two shift id 1 and 2)
I want to run the shift for 6 days. but after each 2 days Shift id 1 rotate to shift id 2 and again after two days shift id 2 rotate to shift id 1 and so on...
My output should be like
04/03/2015=1
05/03/2015=1
06/03/2015=2
07/03/2015=2
08/03/2015=1
09/03/2015=1
I am getting shift id through a foreach loop. I tried like below mentioned way but not getting a proper resul. Please help me solve this issue
SqlCommand cmd2 = new SqlCommand("select ShiftID from ShiftGroup where
ShiftName='" + ide + "'", conn2);
SqlDataAdapter sda2 = new SqlDataAdapter(cmd2);
DataSet ds4 = new DataSet();
var rows2 = ds4.Tables[0].Rows;
if (ds4.Tables[0].Rows.Count > 0)
{
foreach (DataRow row2 in rows2)
{
string shiftname = Convert.ToString(row2["ShiftID"]);
DateTime date=04/03/2015(date)
Total Woring days=6 (total)
Rotation Days=2 (rotationday)
DateTime rotation= date.AddDays(rotationday);//
DateTime totaldate = date.AddDays(workingdays);
for (DateTime rotation = date; rotation <= totaldate; rotation = rotation.AddDays(1))//total working days
{
//to check rotation date
if (rotation <= totaldate )
{
allocation.shiftallocation( rotation, shiftid);
}
}
}
I am stucked with this from last day, anybody help me . No need of consider my for loop, kindly provide a for loop which generate the above mentioned output
You can try this,
DateTime date=DateTime.ParseExact("04/03/2015","dd/MM/yyyy",CultureInfo.InvariantCulture);
DateTime totaldate = date.AddDays(6);
for (int i=0; date <= totaldate; date = date.AddDays(1),i++)//total working days
{
if((i/2)%2==0)
Console.WriteLine(date+" "+1);
else
Console.WriteLine(date+" "+2);
}
Don't use dates at loop cycle, use abstract indicies. You can really abstract from concrete numbers and use only variables for managing result. So you can easily change rotationDays count and even workshifts labels array without changing cycle.
var date = DateTime.Parse("04/03/2015");
var totalWorkingDays = 15;
var rotationDays = 2;
var workshifts = new[] { "S1", "S2" };
var currentWorkshiftIndex = 0;
for (int dayIndex = 0; dayIndex <= totalWorkingDays; dayIndex++) {
if (dayIndex != 0 && dayIndex % rotationDays == 0) currentWorkshiftIndex = (currentWorkshiftIndex + 1) % workshifts.Length;
Console.WriteLine(date.AddDays(dayIndex) + " " + workshifts[currentWorkshiftIndex]);
}
var date = DateTime.Parse("04/03/2015");
var totalWorkingDays = 6;
var rotationDays = 2;
var rotationId = 1;
var rotationCounter = 1;
for (DateTime rotation = date;
rotation <= date.AddDays(totalWorkingDays);
rotation = rotation.AddDays(1))
{
Console.WriteLine(rotation + " " + rotationId);
if (rotationCounter++ == 2)
{
rotationCounter = 1;
rotationId = 3 - rotationId;
}
}
Or, with a linq query
var date = DateTime.Parse("04/03/2015");
var totalWorkingDays = 6;
var rotationDays = 2;
foreach (var d in Enumerable.Range(0, totalWorkingDays)
.Select((i, index) => date.AddDays(i) +
(((int)(index / rotationDays)) % 2 == 1 ? " 2" : " 1")))
{
Console.WriteLine(d);
}
According to your comment for the 5 working days a week, I wrote this:
var start = new DateTime(2015, 04, 03);
var working_day_count = 6;
var rotation_interval = 2;
var shifts = new List<int> { 1, 2 };
var rotation_count = 1;
var shift_index = 0;
for (var i = 0; i < working_day_count; i++) {
while ((start.DayOfWeek == DayOfWeek.Saturday) ||
(start.DayOfWeek == DayOfWeek.Sunday)) {
start = start.AddDays(1);
}
Console.WriteLine(start.ToString() + " = " + shifts[shift_index].ToString());
start = start.AddDays(1);
rotation_count++;
if (rotation_count > rotation_interval) {
rotation_count = 1;
shift_index++;
if (shift_index >= shifts.Count) {
shift_index = 0;
}
}
}
Just change the values of the first four varibales as you like.
I tried to make it easy to understand instead of performant or compact.
A generic solution with holidays taken into account.
int totalDays = 10;
int rotationDays = 3;
int[] shifts = new[] { 1, 2 };
string startDate = "04/03/2015";
var holidays = new List<DayOfWeek>(new[] { DayOfWeek.Saturday, DayOfWeek.Sunday, DayOfWeek.Tuesday });
var shiftAllocations = new Dictionary<DateTime, int>();
int currentShiftIndex = 0;
DateTime current = DateTime.ParseExact(startDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
for (int i = 0; i < totalDays; i += rotationDays)
{
var currentShiftId = shifts[currentShiftIndex];
// For each day from the current day till the number of shift rotation days, allocate the shift.
for (int j = 0; j < rotationDays;)
{
// If the current day is a holiday, move to the next day by incrementing i.
if (holidays.Contains(current.AddDays(i + j).DayOfWeek))
{
i++;
continue;
}
shiftAllocations.Add(current.AddDays(i + j), currentShiftId);
j++;
}
// Increase the shift index if the value is within the bounds. If not reset the index to the beginning
if ((currentShiftIndex + 1) >= shifts.Length)
currentShiftIndex = 0;
else
currentShiftIndex++;
}
foreach (var kvp in shiftAllocations)
{
Console.WriteLine(kvp.Key.ToString("dd/MM/yyyy") + ":" + kvp.Value);
}

show every result of foreach loop

I made a <List>DateTime class which named GetDataRange so that users can get days between two specific days.
Then I want to show days in the columns of data grid view. I use a foreach loop, This loop will cause a problem. The problem is it won't show all days in the columns because I want to show all days in other calendar. see the codes :
for (int i = 0; i < dtEnd.Subtract(dtStart).Days; i++)
{
TimeSpan counter = new TimeSpan(i, 0, 0, 0);
string s1 = "10/9/2012";
string s2 = "11/10/2012";
d1 = Convert.ToDateTime(s1);
d2 = Convert.ToDateTime(s2);
foreach (DateTime item in GetDateRange(d1, d2))
{
s = item.ToShortDateString();
}
PersianCalendar p = new PersianCalendar();
DateTime date = Convert.ToDateTime(s);
int day = p.GetDayOfMonth(date);
int month = p.GetMonth(date);
int year = p.GetYear(date);
string dt = string.Format("{0}/{1}/{2}", year, month, day);
dataGridView1.Columns.Add(string.Format("col{0}", i), string.Format("{0} {1}", (dtStart + counter).DayOfWeek.ToString(), dt));
}
It will show only one day because of that foreach loop. DayOfWeek is working perfectly but the problem is showing the days in foreach loop it will only show one day.
UPDATE
string dt only show one day it won't show other days.
You can't do that. because every time in the loop you are overriding the value. can you show the dates in a new row.
Try this :
for (int i = 0; i < dtEnd.Subtract(dtStart).Days; i++)
{
TimeSpan counter = new TimeSpan(i, 0, 0, 0);
dataGridView1.Columns.Add(string.Format("col{0}", i), string.Format("{0}", (dtStart + counter).DayOfWeek.ToString()));
}
Then add new row for that :
d1 = dtStart;
d2 = dtEnd;
foreach (DateTime item in GetDateRange(d1, d2))
{
int day = p.GetDayOfMonth(item);
int month = p.GetMonth(item);
int year = p.GetYear(item);
string dt1 = string.Format("{0}/{1}/{2}", year, month, day);
listBox1.Items.Add(dt1);
}
dataGridView1.Rows.Add();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
try
{
dataGridView1.Rows[0].Cells[i].Value = listBox1.Items[i];
}
catch (Exception)
{
}
}

Categories