what is the command to insert data into dataset?
what is wrong with the following code:
DataSetReasons.Data_Tracker_RcodeDataTable GRX =
new DataSetReasons.Data_Tracker_RcodeDataTable();
DataSetReasons.Data_Tracker_RcodeRow rowx =
DataSetReasons.Data_Tracker_RcodeRow();
rowx.dtrc_id = 5;
rowx.eval_id = 28;
rowx.dtcr_StaffNum = "505651";
rowx.dtrc_RC1 = "C";
rowx.dtrc_RC2 = "A";
rowx.dtrc_RM1 = 2;
rowx.dtrc_RM2 = 4;
GRX.Rows.Add(rowx);
you must add your datatable GRX to your dataset DataSetReasons.
DataSetReasons.Data_Tracker_RcodeDataTable GRX =
new DataSetReasons.Data_Tracker_RcodeDataTable();
DataSetReasons.Data_Tracker_RcodeRow rowx =
DataSetReasons.Data_Tracker_RcodeRow();
rowx.dtrc_id = 5;
rowx.eval_id = 28;
rowx.dtcr_StaffNum = "505651";
rowx.dtrc_RC1 = "C";
rowx.dtrc_RC2 = "A";
rowx.dtrc_RM1 = 2;
rowx.dtrc_RM2 = 4;
GRX.Rows.Add(rowx);
DataSetReasons.Tables.Add(GRX);//<--
Replace your code with the below line:
DataSetReasons.Data_Tracker_RcodeRow rowx = GRX.NewRow();
Regarding adding the datatable to a dataset, you have to create a dataset object and add the datatable to the dataset.
solved, thanks to everyone... here is the code:
DataSetReasons.Data_Tracker_RcodeDataTable GRX =
new DataSetReasons.Data_Tracker_RcodeDataTable();
GRX.Rows.Add(13, 28, "C", 5, "A", 2, TextBox2.Text);
Related
i had this unbound datagridview that add columns during form load;
here is the code;
private void loadfields()
{
dgvbulkentries.ColumnCount = 15;
dgvbulkentries.Columns[0].Name = "ID No";
dgvbulkentries.Columns[0].Width = 80;
dgvbulkentries.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgvbulkentries.Columns[1].Name = "Surname";
dgvbulkentries.Columns[1].Width = 150;
dgvbulkentries.Columns[2].Name = "First Name";
dgvbulkentries.Columns[2].Width = 150;
dgvbulkentries.Columns[3].Name = "Name Extn";
dgvbulkentries.Columns[3].Width = 40;
dgvbulkentries.Columns[4].Name = "Middle Name";
dgvbulkentries.Columns[4].Width = 150;
dgvbulkentries.Columns[5].Name = "Course";
dgvbulkentries.Columns[5].Width = 110;
dgvbulkentries.Columns[6].Name = "Year";
dgvbulkentries.Columns[6].Width = 40;
dgvbulkentries.Columns[6].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgvbulkentries.Columns[7].Name = "Street/Block";
dgvbulkentries.Columns[7].Width = 150;
dgvbulkentries.Columns[8].Name = "Subdivision";
dgvbulkentries.Columns[8].Width = 150;
dgvbulkentries.Columns[9].Name = "Barangay";
dgvbulkentries.Columns[9].Width = 150;
dgvbulkentries.Columns[10].Name = "Municipality/City";
dgvbulkentries.Columns[10].Width = 150;
dgvbulkentries.Columns[11].Name = "Province";
dgvbulkentries.Columns[11].Width = 150;
dgvbulkentries.Columns[12].Name = "GWA";
dgvbulkentries.Columns[12].Width = 60;
dgvbulkentries.Columns[12].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dgvbulkentries.Columns[13].Name = "Units";
dgvbulkentries.Columns[13].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgvbulkentries.Columns[13].Width = 50;
dgvbulkentries.Columns[14].Name = "Total School Fees";
dgvbulkentries.Columns[14].Width = 100;
dgvbulkentries.Columns[14].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
DataGridViewComboBoxColumn sexes = new DataGridViewComboBoxColumn();
sexes.HeaderText = "Sex";
sexes.Name = "Sex";
sexes.MaxDropDownItems = 4;
sexes.Items.Add("Male");
sexes.Items.Add("Female");
dgvbulkentries.Columns.Add(sexes);
dgvbulkentries.Columns[15].DisplayIndex = 5;
dgvbulkentries.Columns[15].Width = 80;
DataGridViewComboBoxColumn ssfapremarks = new DataGridViewComboBoxColumn();
ssfapremarks.HeaderText = "Remarks";
ssfapremarks.Name = "Remarks";
ssfapremarks.MaxDropDownItems = 4;
ssfapremarks.Items.Add("Enrolled");
ssfapremarks.Items.Add("Not Enrolled");
dgvbulkentries.Columns.Add(ssfapremarks);
dgvbulkentries.Columns[16].Width = 120;
}
I already set the code for currency textbox for a specific column in a datagridview. But the problem is, when i enter numbers in a cell, it does not change at all.
This is the code i included;
private void dgvbulkentries_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
dgvbulkentries.Columns[14].DefaultCellStyle.Format = "n";
}
For example, when i enter numbers to a specific column in the datagridview, it does not format the value as currency format. i already did what you had suggested but its not working
what did i miss?
As mentioned in this answer
After knowing the issue I think using CellLeave event of data grid view will solve ur issue
void dataGridView1_CellLeave(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
dgvbulkentries.Columns[14].DefaultCellStyle.Format = "c2";
dgvbulkentries.Columns[14].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("en-GB");
dgvbulkentries.Columns[14].ValueType = typeof(decimal);
}
Actually, i have two data tables. Here is the code for reference. Actually Relationship holds the sub string values(Code not mentioned here). So i am splitting the data's to store in two table's based on the condition.
if (child.Relationship.Contains("P"))
{
var newRow = dataTable.NewRow();
newRow["EmployeeNo"] = child.EmployeeNo;
newRow["FirstName"] = child.FirstName;
newRow["MiddleName"] = child.MiddleName;
newRow["LastName"] = child.LastName;
newRow["FullName"] = child.FullName;
newRow["MemberIc"] = child.MemberIc;
dataTable.Rows.Add(newRow);
}
else
{
var newRow1 = dataTable1.NewRow();
newRow1["EmployeeNo"] = child.EmployeeNo;
newRow1["FirstName"] = child.FirstName;
newRow1["MiddleName"] = child.MiddleName;
newRow1["LastName"] = child.LastName;
newRow1["FullName"] = child.FullName;
newRow1["MemberIC"] = child.MemberIC;
dataTable1.Rows.Add(newRow1);
}
So, whenever the MemberIc in the second data table is empty. I need to copy the MemberIc from first data table(only if EmployeeNo Matches) based on the EmployeeNo.
How can i copy the value ? Any help appreciated. Thanks in advance !!!
Here you go.
var rows = datatable.Select("EmployeeNo = " + child.EmployeeNo);
var memberIC = 0;
if(rows.length > 0)
{
memberIC = rows[0].Field<int>("memberIC");
}
if (child.Relationship.Contains("P"))
{
var newRow = dataTable.NewRow();
newRow["EmployeeNo"] = child.EmployeeNo;
newRow["FirstName"] = child.FirstName;
newRow["MiddleName"] = child.MiddleName;
newRow["LastName"] = child.LastName;
newRow["FullName"] = child.FullName;
newRow["MemberIc"] = child.MemberIc;
dataTable.Rows.Add(newRow);
}
else
{
var newRow1 = dataTable1.NewRow();
newRow1["EmployeeNo"] = child.EmployeeNo;
newRow1["FirstName"] = child.FirstName;
newRow1["MiddleName"] = child.MiddleName;
newRow1["LastName"] = child.LastName;
newRow1["FullName"] = child.FullName;
newRow1["MemberIC"] = child.MemberIC == 0 ? memberIC : child.MemberIC;
dataTable1.Rows.Add(newRow1);
}
This has nothing to do with C#, ADO.NET or datatable. This is a simple logic of what to check and where to check.
I have a winform in c# that I dynamically created two comboboxes and a textbox. When a user selects say the month and year and enters a value in the text box I want get the related comboboxes values when the button is clicked to save. By default the month and year combobox will have the current month and year selected.
There is also another part in the same screen where data will be populated for the previous month like Jan to March for the current year in the comboboxes and the text boxes if available.
I am not sure whether this approach is correct or I should go with a datagridview. Below is the screenshot and my code. Any suggestions on how I can do this.
Screenshot
Code
private void createComboMonths()
{
int width = 79;
int height = 24;
int spacing = 28;
ComboBox[] SubMonths = new ComboBox[12];
for (int i = 0; i <= 11; ++i)
{
SubMonths[i] = new ComboBox();
SubMonths[i].Name = "SubMonths";
SubMonths[i].DropDownStyle = ComboBoxStyle.DropDownList;
SubMonths[i].Size = new Size(width, height);
SubMonths[i].Location = new Point(56, (i * height) + spacing);
SubMonths[i].Items.Add("January");
SubMonths[i].Items.Add("February");
SubMonths[i].Items.Add("March");
SubMonths[i].Items.Add("April");
SubMonths[i].Items.Add("May");
SubMonths[i].Items.Add("June");
SubMonths[i].Items.Add("July");
SubMonths[i].Items.Add("August");
SubMonths[i].Items.Add("September");
SubMonths[i].Items.Add("October");
SubMonths[i].Items.Add("November");
SubMonths[i].Items.Add("December");
SubMonths[i].SelectedItem = DateTime.Today.ToString("MMMM");
plSubscription.Controls.Add(SubMonths[i]);
}
}
private void createComboYears()
{
int width = 79;
int height = 24;
int spacing = 28;
ComboBox[] SubYears = new ComboBox[12];
for (int i = 0; i <= 11; ++i)
{
SubYears[i] = new ComboBox();
SubYears[i].Name = "SubYears";
SubYears[i].DropDownStyle = ComboBoxStyle.DropDownList;
SubYears[i].Size = new Size(width, height);
SubYears[i].Location = new Point(145, (i * height) + spacing);
plSubscription.Controls.Add(SubYears[i]);
fillComboData(SubYears[i]); // Function to fill the last 5 years
}
}
private void createTextBoxes()
{
int width = 79;
int height = 24;
int spacing = 28;
TextBox[] subAmt = new TextBox[12];
for (int i = 0; i <= 11; ++i)
{
subAmt[i] = new TextBox();
subAmt[i].Name = "SubAmt" + i;
subAmt[i].Border.Class = "TextBoxBorder";
subAmt[i].Size = new Size(width, height);
subAmt[i].Margin = new Padding(10, 10, 10, 10);
subAmt[i].Location = new Point(279, (i * height) + spacing);
subAmt[i].KeyPress += new KeyPressEventHandler(txtJanAmt_KeyPress);
plSubscription.Controls.Add(subAmt[i]);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
DataTable dtSubs = new DataTable();
dtSubs.Columns.Add("SubscriberID", typeof(string));
dtSubs.Columns.Add("Month", typeof(string));
dtSubs.Columns.Add("Year", typeof(string));
dtSubs.Columns.Add("SubAmt", typeof(string));
DataRow row = dtSubs.NewRow();
foreach (Control c in plSubscription.Controls)
{
//<- Not sure how do I get the selected row as in the screenshot
}
}
EDIT 1
I used the below code that gets the data from the datatable but not able to do the following
How do I set the value of the comboboxes as selected when I get it from the datatable
For the textbox how do I get the value from the datatable
Whenever there is data available I want that row to be readonly.
Thanks in advance
Changed code
for (int i = 0; i < dt.Rows.Count; i++)
{
#region Grid Column Names
DataGridViewComboBoxColumn mntCmb = new DataGridViewComboBoxColumn();
mntCmb.HeaderText = "Month";
mntCmb.Name = "Month";
mntCmb.DataSource = dt;
mntCmb.DisplayMember = "paidformonth";
mntCmb.ValueMember = "paidformonth";
// <-How do I set the column as selected.
DataGridViewComboBoxColumn yearCmb = new DataGridViewComboBoxColumn();
yearCmb.HeaderText = "Year";
yearCmb.Name = "Year";
yearCmb.DisplayMember = "paidforyear";
yearCmb.ValueMember = "paidforyear";
// <-How do I set the column as selected.
DataGridViewTextBoxColumn amount = new DataGridViewTextBoxColumn();
amount.HeaderText = "Subscription Amount";
amount.Name = "Subscription Amount";
amount.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
// <-How do I set this column with the value from the datatable
#endregion
dgvSubscriptions.Columns.AddRange(mntCmb, yearCmb, amount);
}
Edit 2
I seem to be confused as to why I am getting 3 rows with 6 columns. The datatable only has 2 rows and 3 columns. I am using the above code. I added the ID column just to see what happens. See the screenshot below. I have
dgvSubscriptions.AllowUserToAddRows = true
as I want the user to add rows and enter more data to save. What I am trying to do here is to get a subscription list of months/years that were paid and allow users to add subscription for say May, June assuming Jan to April was paid.
Edit 3
I even set the DataPropertyName instead of the ValueMember still no changes
Edited Code
DataGridViewComboBoxColumn yearCmb = new DataGridViewComboBoxColumn();
yearCmb.HeaderText = "Year";
yearCmb.Name = "Year";
//yearCmb.DataSource = dt;
yearCmb.DisplayMember = "paidforyear";
//yearCmb.ValueMember = "paidforyear";
yearCmb.DataPropertyName= "paidforyear";
yearCmb.DefaultCellStyle.NullValue = dt.Rows[i][2].ToString();
yearCmb.ReadOnly = true;
dgvSubscriptions.Columns.Add(yearCmb);
Edit 4
Below is the actual code that is causing the duplicate columns
dgvSubscriptions.AutoGenerateColumns = false;
dgvSubscriptions.ColumnCount = 1;
dgvSubscriptions.Columns[0].Name = "ID";
dgvSubscriptions.Rows.Clear();
for (int i = 0; i <dt.Rows.Count; i++)
{
dgvSubscriptions.Rows.Add();
#region Grid Column Names
DataGridViewComboBoxColumn mntCmb = new DataGridViewComboBoxColumn();
mntCmb.HeaderText = "Month";
mntCmb.Name = "Month";
//mntCmb.DataSource = dt;
mntCmb.DisplayMember = "paidformonth";
mntCmb.DataPropertyName = "paidformonth";
//mntCmb.ValueMember = "paidformonth";
mntCmb.DefaultCellStyle.NullValue = dt.Rows[i][1].ToString();
mntCmb.ReadOnly = true;
dgvSubscriptions.Columns.Add(mntCmb);
DataGridViewComboBoxColumn yearCmb = new DataGridViewComboBoxColumn();
yearCmb.HeaderText = "Year";
yearCmb.Name = "Year";
//yearCmb.DataSource = dt;
yearCmb.DisplayMember = "paidforyear";
//yearCmb.ValueMember = "paidforyear";
yearCmb.DataPropertyName= "paidforyear";
yearCmb.DefaultCellStyle.NullValue = dt.Rows[i][2].ToString();
yearCmb.ReadOnly = true;
dgvSubscriptions.Columns.Add(yearCmb);
DataGridViewTextBoxColumn amount = new DataGridViewTextBoxColumn();
amount.HeaderText = "Subscription Amount";
amount.Name = "Subscription Amount";
amount.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
//amount.DataPropertyName = dt.Rows[i][2].ToString();
amount.DataPropertyName="subamount";
amount.DefaultCellStyle.NullValue = dt.Rows[i][0].ToString();
amount.ReadOnly = true;
dgvSubscriptions.Columns.Add(amount);
#endregion
}
Edit 5
I used IRSOG code with some modification and below is the full working code.
Working Code
public struct Data
{
public List<string> Mon { get; set; }
public List<string> Year { get; set; }
}
private void fillGridData(DataTable dt)
{
List<string> Mon = new List<string>() { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
List<string> Year = new List<string>();
int CurrentYear = DateTime.UtcNow.Year;
int NextYear = CurrentYear + 1;
int LastFiveYears = CurrentYear - 5;
for (int i = LastFiveYears; i <= NextYear; i++)
{
Year.Add(i.ToString());
}
List<Data> _Data = new List<Data>();
for (int i = 1; i <= 12; i++)
{
_Data.Add(new Data() { Mon = Mon, Year = Year });
}
dgvSubscriptions.Rows.Clear();
dgvSubscriptions.Refresh();
dgvSubscriptions.Visible = true;
dgvSubscriptions.ColumnHeadersDefaultCellStyle.Font = new Font("Trebuchet MS", 8F, FontStyle.Regular);
dgvSubscriptions.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dgvSubscriptions.AutoResizeColumns();
dgvSubscriptions.AllowUserToResizeColumns = true;
dgvSubscriptions.AllowUserToOrderColumns = true;
dgvSubscriptions.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgvSubscriptions.Dock = DockStyle.None;
dgvSubscriptions.BackgroundColor = this.BackColor;
dgvSubscriptions.BorderStyle = BorderStyle.None;
dgvSubscriptions.AllowUserToAddRows = true;
// If dt.Rows.Count > 0 then show the data - do not allow to change existing data
if (dt.Rows.Count > 0)
{
dgvSubscriptions.Rows.Clear();
dgvSubscriptions.Refresh();
#region Grid Column Names
dgvSubscriptions.AutoGenerateColumns = false;
dgvSubscriptions.Rows.Clear();
DataGridViewComboBoxColumn mntCmb = new DataGridViewComboBoxColumn();
mntCmb.HeaderText = "Month";
mntCmb.Name = "Month";
mntCmb.DataSource = Mon;
mntCmb.DefaultCellStyle.NullValue = "";
dgvSubscriptions.Columns.Add(mntCmb);
DataGridViewComboBoxColumn yearCmb = new DataGridViewComboBoxColumn();
yearCmb.HeaderText = "Year";
yearCmb.Name = "Year";
yearCmb.DataSource = Year;
yearCmb.DefaultCellStyle.NullValue = "";
dgvSubscriptions.Columns.Add(yearCmb);
DataGridViewTextBoxColumn amount = new DataGridViewTextBoxColumn();
amount.HeaderText = "Subscription Amount";
amount.Name = "Subscription Amount";
amount.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
amount.DefaultCellStyle.NullValue = "";
dgvSubscriptions.Columns.Add(amount);
#endregion
#region Populate Grid
for (int i = 0; i <dt.Rows.Count; i++)
{
dgvSubscriptions.Rows.Add();
dgvSubscriptions.Rows[i].Cells[0].Value = dt.Rows[i][1].ToString(); // Month
dgvSubscriptions.Rows[i].Cells[0].ReadOnly = true; // do not allow the user to make changes
dgvSubscriptions.Rows[i].Cells[1].Value = dt.Rows[i][2].ToString(); // Year
dgvSubscriptions.Rows[i].Cells[1].ReadOnly = true; // do not allow the user to make changes
dgvSubscriptions.Rows[i].Cells[2].Value = dt.Rows[i][0].ToString(); // Subscription amount
dgvSubscriptions.Rows[i].Cells[2].ReadOnly = true; // do not allow the user to make changes
}
#endregion
}
else // We come here if dt.Rows.Count is 0 we allow the user to select and save
{
#region Grid Column Names
DataGridViewComboBoxColumn mntCmb = new DataGridViewComboBoxColumn();
mntCmb.HeaderText = "Month";
mntCmb.Name = "Month";
mntCmb.DataSource = Mon;
DataGridViewComboBoxColumn yearCmb = new DataGridViewComboBoxColumn();
yearCmb.HeaderText = "Year";
yearCmb.Name = "Year";
yearCmb.DataSource = Year;
DataGridViewTextBoxColumn amount = new DataGridViewTextBoxColumn();
amount.HeaderText = "Subscription Amount";
amount.Name = "Subscription Amount";
amount.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
#endregion
dgvSubscriptions.Columns.AddRange(mntCmb, yearCmb, amount);
dgvSubscriptions.DataSource = _Data;
}
dgvSubscriptions.RowsDefaultCellStyle.Font = new Font("Trebuchet MS", 8F, FontStyle.Regular);
}
Instead of using this,use DataGridView
Try this:
With Calling GetCurrentRowValues method you can get selected row information's.
Complete Code
public Form1()
{
InitializeComponent();
dataGridView1.MultiSelect = false;
}
private void Form1_Load(object sender, EventArgs e)
{
List<string> Mon = new List<string>() { "January", "February", "March", "April", "May", " June", "July", "August", "September", "October", "November", "December" };
List<string> Year = new List<string>() { "2001", "2002", "2003", "2004", "2005", "2006" };
List<Data> _Data = new List<Data>();
for (int i = 1; i <= 12; i++)
{
_Data.Add(new Data() { Mon = Mon, Year = Year });
}
DataGridViewComboBoxColumn moonCmb = new DataGridViewComboBoxColumn();
moonCmb.HeaderText = "Month";
moonCmb.Name = "Month";
moonCmb.DataSource = Mon;
DataGridViewComboBoxColumn yearCmb = new DataGridViewComboBoxColumn();
yearCmb.HeaderText = "Year";
yearCmb.Name = "Year";
yearCmb.DataSource = Year;
DataGridViewTextBoxColumn amount = new DataGridViewTextBoxColumn();
amount.HeaderText = "Amount";
amount.Name = "Amount";
dataGridView1.Columns.AddRange(moonCmb, yearCmb, amount);
dataGridView1.DataSource = _Data;
}
private void GetCurrentRowValues()
{
var mon = dataGridView1.CurrentRow.Cells["Month"].Value;
var year = dataGridView1.CurrentRow.Cells["Year"].Value;
var amont = dataGridView1.CurrentRow.Cells["Amount"].Value;
}
}
public struct Data
{
public List<string> Mon { get; set; }
public List<string> Year { get; set; }
}
Result
New edit-From data table
#region Grid Column Names
dgvSubscriptions.AutoGenerateColumns = false;
dgvSubscriptions.ColumnCount = 1;
dgvSubscriptions.Columns[0].Name = "ID";
dgvSubscriptions.Rows.Clear();
DataGridViewComboBoxColumn mntCmb = new DataGridViewComboBoxColumn();
mntCmb.HeaderText = "Month";
mntCmb.Name = "Month";
//mntCmb.DataSource = dt;
mntCmb.DisplayMember = "paidformonth";
mntCmb.DataPropertyName = "paidformonth";
//mntCmb.ValueMember = "paidformonth";
mntCmb.DefaultCellStyle.NullValue = "";
mntCmb.ReadOnly = true;
mntCmb.Items.Add("april");
mntCmb.Items.Add("jun");
mntCmb.Items.Add("jull");
dgvSubscriptions.Columns.Add(mntCmb);
DataGridViewComboBoxColumn yearCmb = new DataGridViewComboBoxColumn();
yearCmb.HeaderText = "Year";
yearCmb.Name = "Year";
//yearCmb.DataSource = dt;
yearCmb.DisplayMember = "paidforyear";
//yearCmb.ValueMember = "paidforyear";
yearCmb.DataPropertyName = "paidforyear";
yearCmb.DefaultCellStyle.NullValue = "";
yearCmb.Items.Add("2001");
yearCmb.Items.Add("2002");
yearCmb.Items.Add("2003");
yearCmb.ReadOnly = true;
dgvSubscriptions.Columns.Add(yearCmb);
DataGridViewTextBoxColumn amount = new DataGridViewTextBoxColumn();
amount.HeaderText = "Subscription Amount";
amount.Name = "Subscription Amount";
amount.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
//amount.DataPropertyName = dt.Rows[i][2].ToString();
amount.DataPropertyName = "subamount";
amount.DefaultCellStyle.NullValue = "";
amount.ReadOnly = true;
dgvSubscriptions.Columns.Add(amount);
#endregion
Fill it
for (int i = 0; i < dt.Rows.Count; i++)
{
dgvSubscriptions.Rows.Add();
dgvSubscriptions.Rows[i].Cells[0].Value = dt.Rows[i][0].ToString();
dgvSubscriptions.Rows[i].Cells[1].Value = dt.Rows[i][1].ToString();
dgvSubscriptions.Rows[i].Cells[2].Value = dt.Rows[i][2].ToString();
dgvSubscriptions.Rows[i].Cells[3].Value = dt.Rows[i][0].ToString();
}
The forms ActiveControl property can help you.
var focusedCtrl = this.ActiveControl;
var siblings = Controls.Where(c => c.Location.Y == focusedCtrl.Location.Y).ToList();
foreach (Control c in siblings)
{
// all thise controls are on the same row, providede that the allign
}
Still I would sugget the DataGridView. It seems to be a better choise for a structure that looks like yours.
I’d go with the DataGridView but if you still want to keep this structure you might want to update KeyPressed event handler to look something like this
private string lastUsedTextBox = string.Empty;
private string lastEnteredValue = string.Empty;
private void txtJanAmt_KeyPress(object sender, KeyPressEventArgs e)
{
lastUsedTextBox = (sender as TextBox).Name;
lastEnteredValue = (sender as TextBox).Text;
}
And then when you press the save button you have everything stored here.
If you need to save all the data you can use dictionary or something like that.
Does anyone know how to do this?
I'm using EPPlus in .Net and have created a pivot table with 2 row fields and one summary datafield:
Dim Pivot As OfficeOpenXml.Table.PivotTable.ExcelPivotTable
Pivot = wksPivot.PivotTables.Add(wksPivot.Cells("A1"), Datarange, "pName")
Pivot.RowFields.Add(Pivot.Fields("Fld1")).Sort = Table.PivotTable.eSortType.Ascending
Pivot.RowFields.Add(Pivot.Fields("Fld2")).Sort = Table.PivotTable.eSortType.Ascending
Dim dtaFld As OfficeOpenXml.Table.PivotTable.ExcelPivotTableDataField
dtaFld = Pivot.DataFields.Add(Pivot.Fields("XYZ"))
dtaFld.Function = Table.PivotTable.DataFieldFunctions.Sum
Everything works great, but I want to have the Pivot Table start off as collapsed when the user opens the workbook (In excel, when you're creating the pivot table, you can right-click in the data element and select "Expand / Collapse" > "Collapse Entire Field"
Hot can I do this via code?? (And I'm willing to use direct OpenXML if EPPlus doesn't support this yet...)
ALSO, is there a way to delete out the Raw data from the workbook so that the pivot table still works? i've tried and when I open the workbook, my pivot table is blank? - My current logic has led me to this question... Any thoughts??
(I do know I wrote this question in VB. but I added both the C# & VB tags to this question - I'm comfortable with code in either language - Thanks!!)
Could make it xlsm and add vba to it. This is probably the worst answer to this solution but it achives full collapse. I have provided a working example, just copy past into a new console app. add the epplus dependency, "F5".
modified/taken from http://epplus.codeplex.com/SourceControl/latest#SampleApp/Sample15.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OfficeOpenXml.Table;
using OfficeOpenXml.Table.PivotTable;
using OfficeOpenXml;
using System.IO;
namespace pTable
{
class Program
{
static void Main(string[] args)
{
//ExcelPackage _pck = new ExcelPackage();
Directory.CreateDirectory(string.Format("Test"));
//ExcelPackage _pck = new ExcelPackage(new FileInfo("Test\\Worksheet.xlsx"));
ExcelPackage _pck = new ExcelPackage(new FileInfo("Test\\Worksheet.xlsm"));
var wsPivot1 = _pck.Workbook.Worksheets.Add("Rows-Data on columns");
var ws = _pck.Workbook.Worksheets.Add("Data");
ws.Cells["K1"].Value = "Item";
ws.Cells["L1"].Value = "Category";
ws.Cells["M1"].Value = "Stock";
ws.Cells["N1"].Value = "Price";
ws.Cells["O1"].Value = "Date for grouping";
ws.Cells["K2"].Value = "Crowbar";
ws.Cells["L2"].Value = "Hardware";
ws.Cells["M2"].Value = 12;
ws.Cells["N2"].Value = 85.2;
ws.Cells["O2"].Value = new DateTime(2010, 1, 31);
ws.Cells["K3"].Value = "Crowbar";
ws.Cells["L3"].Value = "Hardware";
ws.Cells["M3"].Value = 15;
ws.Cells["N3"].Value = 12.2;
ws.Cells["O3"].Value = new DateTime(2010, 2, 28);
ws.Cells["K4"].Value = "Hammer";
ws.Cells["L4"].Value = "Hardware";
ws.Cells["M4"].Value = 550;
ws.Cells["N4"].Value = 72.7;
ws.Cells["O4"].Value = new DateTime(2010, 3, 31);
ws.Cells["K5"].Value = "Hammer";
ws.Cells["L5"].Value = "Hardware";
ws.Cells["M5"].Value = 120;
ws.Cells["N5"].Value = 11.3;
ws.Cells["O5"].Value = new DateTime(2010, 4, 30);
ws.Cells["K6"].Value = "Crowbar";
ws.Cells["L6"].Value = "Hardware";
ws.Cells["M6"].Value = 120;
ws.Cells["N6"].Value = 173.2;
ws.Cells["O6"].Value = new DateTime(2010, 5, 31);
ws.Cells["K7"].Value = "Hammer";
ws.Cells["L7"].Value = "Hardware";
ws.Cells["M7"].Value = 1;
ws.Cells["N7"].Value = 4.2;
ws.Cells["O7"].Value = new DateTime(2010, 6, 30);
ws.Cells["K8"].Value = "Saw";
ws.Cells["L8"].Value = "Hardware";
ws.Cells["M8"].Value = 4;
ws.Cells["N8"].Value = 33.12;
ws.Cells["O8"].Value = new DateTime(2010, 6, 28);
ws.Cells["K9"].Value = "Screwdriver";
ws.Cells["L9"].Value = "Hardware";
ws.Cells["M9"].Value = 1200;
ws.Cells["N9"].Value = 45.2;
ws.Cells["O9"].Value = new DateTime(2010, 8, 31);
ws.Cells["K10"].Value = "Apple";
ws.Cells["L10"].Value = "Groceries";
ws.Cells["M10"].Value = 807;
ws.Cells["N10"].Value = 1.2;
ws.Cells["O10"].Value = new DateTime(2010, 9, 30);
ws.Cells["K11"].Value = "Butter";
ws.Cells["L11"].Value = "Groceries";
ws.Cells["M11"].Value = 52;
ws.Cells["N11"].Value = 7.2;
ws.Cells["O11"].Value = new DateTime(2010, 10, 31);
ws.Cells["O2:O11"].Style.Numberformat.Format = "yyyy-MM-dd";
var pt = wsPivot1.PivotTables.Add(wsPivot1.Cells["A1"], ws.Cells["K1:N11"], "Pivottable1");
pt.Compact = true;
pt.CompactData = true;
pt.GrandTotalCaption = "Total amount";
pt.RowFields.Add(pt.Fields[1]);
pt.RowFields.Add(pt.Fields[0]);
pt.DataFields.Add(pt.Fields[3]);
pt.DataFields.Add(pt.Fields[2]);
pt.DataFields[0].Function = DataFieldFunctions.Product;
pt.DataOnRows = false;
_pck.Workbook.CreateVBAProject();
var sb = new StringBuilder();
sb.AppendLine("Private Sub Workbook_Open()");
sb.AppendLine(" Range(\"A1\").Select");
sb.AppendLine(" ActiveSheet.PivotTables(\"Pivottable1\").PivotFields(\"Category\").PivotItems(\"Hardware\").ShowDetail = False");
sb.AppendLine("End Sub");
_pck.Workbook.CodeModule.Code = sb.ToString();
_pck.Save();
}
}
}
Using EPPlus you could try something like (Taken from this SO post):
(from pf in pivot.Fields
select pf).ToList().ForEach(f =>
{
f.Compact = false;
f.Outline = false;
});
or perhaps more simply, doesn't something like the following work?
pvtTable.Compact = False
pvtTable.CompactData = False
pvtTable.Outline = False
pvtTable.OutlineData = False
pvtTable.ShowDrill = True
Also look at this SO post detailing a nice reverse engineer method for seeing how excel achieves 'things'.
P.S. Can't help you with your other 'also' question sorry.
I would like to do a plot with time function of data by using ultrachart , infragistics.
I have found this sample :
DataTable Recap = MarketData.Tables.Add("Recap");
// on ajoute des column a recap ne pas oublier de typer les colonnes
Recap.Columns.Add("Date", typeof(DateTime));
Recap.Columns.Add("Move Ticker price", typeof(double));
Recap.Columns.Add("Move Index price", typeof(double));
Recap.Columns.Add("Alpha",typeof (double));
// on remplie recap
for (int i = 0; i < TickerPrice.Rows.Count; i++)
{
DataRow destRow = Recap.NewRow();
destRow["Move Ticker price"] = TickerPrice.Rows[i]["CHG_PCT_1D"];
destRow["Move Index price"] = IndexPrice.Rows[i]["CHG_PCT_1D"];
destRow["Date"] = TickerPrice.Rows[i]["Date"];
Recap.Rows.Add(destRow);
}
// calcul du alpha
foreach (DataRow dr in Recap.Rows)
dr["Alpha"] = ((double)dr["Move Index price"]) * 1.5 - (double)dr["Move Ticker price"];
// remplir le feed alpha
FeedAlpha.DataSource = Recap;
// faire un plot
ChartPureAlpha.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.Composite;
ChartArea myChartArea = new ChartArea();
ChartPureAlpha.CompositeChart.ChartAreas.Add(myChartArea);
// Defines axes
AxisItem axisX = new AxisItem();
axisX.DataType = Infragistics.UltraChart.Shared.Styles.AxisDataType.Numeric;
axisX.Labels.ItemFormatString = "<DATA_VALUE:0.00>";
axisX.SetLabelAxisType = SetLabelAxisType.ContinuousData;
axisX.OrientationType = Infragistics.UltraChart.Shared.Styles.AxisNumber.X_Axis;
axisX.RangeType = AxisRangeType.Custom;
axisX.RangeMin = -1;
axisX.RangeMax = 1;
myChartArea.Axes.Add(axisX);
AxisItem axisY = new AxisItem();
axisY.DataType = Infragistics.UltraChart.Shared.Styles.AxisDataType.Numeric;
axisY.Labels.ItemFormatString = "<DATA_VALUE:0.00>";
axisY.Labels.HorizontalAlign = StringAlignment.Far;
axisY.SetLabelAxisType = SetLabelAxisType.ContinuousData;
axisY.OrientationType = Infragistics.UltraChart.Shared.Styles.AxisNumber.Y_Axis;
axisY.RangeType = AxisRangeType.Custom;
axisY.RangeMin = -1;
axisY.RangeMax = 1;
myChartArea.Axes.Add(axisY);
// Create and add series
XYSeries BPLseries = new XYSeries();
BPLseries.Label = "Blood L";
for (int i = 0; i < Recap.Rows.Count; i++)
BPLseries.Points.Add(new XYDataPoint((double)(Recap.Rows[i][2]), (double)Recap.Rows[i][1], "", false));
// Add a chartLayerAppearance
ChartLayerAppearance myScatterLayer = new ChartLayerAppearance();
myScatterLayer.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.ScatterChart;
myScatterLayer.ChartArea = myChartArea;
myScatterLayer.AxisX = axisX;
myScatterLayer.AxisY = axisY;
myScatterLayer.Series.Add(BPLseries);
ScatterChartAppearance sca1 = new ScatterChartAppearance();
sca1.ConnectWithLines = true;
sca1.Icon = SymbolIcon.None;
myScatterLayer.ChartTypeAppearance = sca1;
ChartPureAlpha.Series.Add(BPLseries);
ChartPureAlpha.CompositeChart.ChartLayers.Add(myScatterLayer);
CompositeLegend myLegend = new CompositeLegend();
myLegend.ChartLayers.Add(myScatterLayer);
myLegend.Bounds = new Rectangle(88, 2, 11, 15);
myLegend.BoundsMeasureType = MeasureType.Percentage;
myLegend.PE.ElementType = PaintElementType.Gradient;
myLegend.PE.FillGradientStyle = GradientStyle.ForwardDiagonal;
myLegend.PE.Fill = Color.CornflowerBlue;
myLegend.PE.FillStopColor = Color.Transparent;
myLegend.Border.CornerRadius = 10;
myLegend.Border.Thickness = 1;
ChartPureAlpha.CompositeChart.Legends.Add(myLegend);
It is working fine if I have data vs data but what I want is time (dd/mm/yyy) vs (double).
Please let me know if you have any idea.
Thanks
You can use the following code to get a time vs data chart:
using Infragistics.Win.UltraWinChart;
using Infragistics.UltraChart.Resources.Appearance;
DataTable dt = new DataTable();
dt.Columns.Add("Value", typeof(double));
dt.Columns.Add("Date", typeof(DateTime));
dt.Rows.Add(1.0, DateTime.Parse("04/20/2012"));
dt.Rows.Add(0.5, DateTime.Parse("04/21/2012"));
dt.Rows.Add(0.25, DateTime.Parse("04/22/2012"));
dt.Rows.Add(0.125, DateTime.Parse("04/23/2012"));
dt.Rows.Add(0.0625, DateTime.Parse("04/24/2012"));
dt.Rows.Add(0.03125, DateTime.Parse("04/25/2012"));
dt.Rows.Add(0.015625, DateTime.Parse("04/26/2012"));
dt.Rows.Add(0.0, DateTime.Parse("04/27/2012"));
NumericTimeSeries series = new NumericTimeSeries();
series.DataBind(dt, "Date", "Value");
UltraChart ultraChart = new UltraChart();
ultraChart.Data.SwapRowsAndColumns = true;
ultraChart.Dock = DockStyle.Fill;
ultraChart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.LineChart;
ultraChart.DataSource = dt;
this.Controls.Add(ultraChart);