C# GoogleSheets API Inserting row to 2nd row? - c#

How do i insert a blank row into the 2nd row?
BatchUpdateSpreadsheetRequest requestBody = new
BatchUpdateSpreadsheetRequest();
requestBody.Requests = new List<Request>();
Request r = new Request();
requestBody.Requests.Add(r);
r.InsertDimension = new InsertDimensionRequest();
var dr = new DimensionRange();
dr.SheetId = 0;
dr.Dimension="ROW";
dr.StartIndex = 0;
dr.EndIndex = 3;
r.InsertDimension.Range = dr;
r.InsertDimension.InheritFromBefore = false;
SpreadsheetsResource.BatchUpdateRequest bur =
service.Spreadsheets.BatchUpdate(requestBody, spreadsheetId);
bur.Execute();
This code adds 2 blank rows as specified in the sheets
I'm refering to page https://developers.google.com/sheets/api/samples/rowcolumn

Related

How to change column height in Google sheets C#

I'm trying to modify the row height in Google sheets of a row I just added. The row consists of a list of strings (i.e. cells). First I add the row, then I try to modify the height:
// I need to convert my list of strings into a list of objects
// there's probably a better way to do this...
var valueRange = new ValueRange();
var oblist = new List<object>();
foreach (var thing in columns)
{
oblist.Add(thing);
}
valueRange.Values = new List<IList<object>>() { oblist };
var appendRequest = service.Spreadsheets.Values.Update(valueRange, spreadsheetId, $"{sheetname}!A{rownumber}:Z{rownumber}");
appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
var appendResponse = appendRequest.Execute();
// now change the row height to 100 pixels.
BatchUpdateSpreadsheetRequest r = new BatchUpdateSpreadsheetRequest();
UpdateDimensionPropertiesRequest request = new UpdateDimensionPropertiesRequest());
request.Range = new DimensionRange();
request.Range.SheetId = sheetId;
request.Range.Dimension = "ROWS";
request.Range.StartIndex =
request.Range.EndIndex = rownumber;
request.Properties = new DimensionProperties();
request.Properties.PixelSize = 100;
request.Fields = "pixelSize";
r.Requests.Add(request);
var bu = service.Spreadsheets.BatchUpdate(r, spreadsheetId);
bu.Execute();
The problem is in the third-last line where I can't add request to the Requests list, as request is not derived from the Request class.
Instead of trying to add the request directly to the batch, I need to add a Requests list to the batch, and then add the request to the Requests list:
UpdateDimensionPropertiesRequest request = new UpdateDimensionPropertiesRequest();
request.Range = new DimensionRange();
request.Range.SheetId = sheetId;
request.Range.Dimension = "ROWS";
request.Range.StartIndex = firstrow;
request.Properties = new DimensionProperties();
request.Properties.PixelSize = 100;
request.Fields = "pixelSize";
// now add the request to the batch
BatchUpdateSpreadsheetRequest busr = new BatchUpdateSpreadsheetRequest();
busr.Requests = new List<Request>();
busr.Requests.Add(new Request { UpdateDimensionProperties = request });
var bur = service.Spreadsheets.BatchUpdate(busr, spreadsheetId);
bur.Execute();

How do you fill a List<Request>() for a BatchUpdateSpreadsheetRequest to update multiple rows/columns/cells in a google spreadsheet in C#

BatchUpdateSpreadsheetRequest requestBody = new BatchUpdateSpreadsheetRequest();
requestBody.Requests = new List<Request>();
Request r = new Request();
requestBody.Requests.Add(r);
r.UpdateCells = new UpdateCellsRequest();
var gc = new GridCoordinate();
gc.ColumnIndex = 0;
gc.RowIndex = 0;
gc.SheetId = 0;
r.UpdateCells.Start = gc;
r.UpdateCells.Fields = "*";
r.UpdateCells.Rows = new List<RowData>();
//TODO:: loop through record set to update cell data (cd) with values to insert
SqlDataReader reader = default(SqlDataReader);
reader = o_cSQL.RunSPReturnDataReader("Shippments", 40997, sNow, sNow);
while (reader.Read())
{
var rd = new RowData();
r.UpdateCells.Rows.Add(rd);
rd.Values = new List<CellData>();
var cd = new CellData();
cd.UserEnteredValue = new ExtendedValue();
// the next line is only updating the first cell (first row/first column)
//how to you get multiple CellData created for a single row ?
cd.UserEnteredValue.StringValue = reader["new_attn"].ToString();
rd.Values.Add(cd);
}
SpreadsheetsResource.BatchUpdateRequest batchRequest = service.Spreadsheets.BatchUpdate(requestBody, spreadsheetId);
batchRequest.Execute();
Can someone please help with how you get multiple cells updated per row ?
I know I'm only showing one value from my 'reader' from the database, that's where I got stuck in that I don't know how to specifically pinpoint each cell of my spreadsheet. I'm pulling an unknown recordset size from a database and need to enter it on a google spreadsheet. I know how many columns.
Since I know my columns, I just kept making new CellData(); items for each RowData item in my reader.Read() while looping. Worked first time!

requests[0]' (oneof), oneof field 'kind' is already set. Cannot set 'updateCell encountered when generating checkbox

I'm trying to generate a checkbox from C#.net using google sheets API but I'm encountering the oneof field kind is already set error. I tried combining extendedValue and DataValidation. Please see code snippet below:
ConditionValue conditionValueTrue = new ConditionValue();
conditionValueTrue.UserEnteredValue = "TRUE";
ConditionValue conditionValueFalse = new ConditionValue();
conditionValueFalse.UserEnteredValue = "FALSE";
ConditionValue[] validValues = { conditionValueTrue, conditionValueFalse };
BooleanCondition bc = new BooleanCondition();
bc.Type = "BOOLEAN";
bc.Values = validValues;
DataValidationRule dataValidationRule = new DataValidationRule();
dataValidationRule.Condition = bc;
dataValidationRule.ShowCustomUi = true;
GridRange validationRange = new GridRange();
validationRange.StartColumnIndex = 7;
validationRange.EndColumnIndex = 7;
validationRange.SheetId = 0;
SetDataValidationRequest setDataValidationRequest = new SetDataValidationRequest();
setDataValidationRequest.Rule = dataValidationRule;
setDataValidationRequest.Range = validationRange;
ExtendedValue extendedValue = new ExtendedValue();
extendedValue.BoolValue = true;
BatchUpdateSpreadsheetRequest busr = new BatchUpdateSpreadsheetRequest();
busr.Requests = new List<Request>();
Request r = new Request();
busr.Requests.Add(r);
r.UpdateCells = new UpdateCellsRequest();
r.SetDataValidation = setDataValidationRequest;
var gc = new GridCoordinate();
gc.ColumnIndex = 7;
gc.RowIndex = row;
gc.SheetId = 0;
r.UpdateCells.Start = gc;
r.UpdateCells.Fields = "*";
r.UpdateCells.Rows = new List<RowData>();
var rd = new RowData();
r.UpdateCells.Rows.Add(rd);
rd.Values = new List<CellData>();
var cd = new CellData();
cd.UserEnteredValue = extendedValue;
rd.Values.Add(cd);
SpreadsheetsResource.BatchUpdateRequest bur = _sheetsService.Spreadsheets.BatchUpdate(busr, SpreadsheetId);
bur.Execute();

DataTable Row Count is Empty

I'm attempting to take a list of Contacts that are retrieved from an OleDB query, add them to a List and then load the List into a DataTable. When I count the number of items in the list it results in the correct number (27000).
However, when I count the number of rows in the DataTable, it results in 0. After doing this I want to write the DataTable to CSV using FileHelpers, however the CSV file is empty.
This is the code I am using;
var listOfContacts = new List<Contact>();
using (OleDbConnection dbfCon = new OleDbConnection(dbfConstr))
{
dbfCon.Open();
var dbfCmd = new OleDbCommand(#"SELECT ct_id, ct_cmpid, ct_empid,
ct_pplid, ct_cntid, ct_pplnm, ct_date, ct_time, ct_type, ct_doneby, ct_desc
FROM contacts", dbfCon);
using (var myReader = dbfCmd.ExecuteReader())
{
while (myReader.Read())
{
var newContact = new Contact()
{
ContactID = Convert.ToInt32(myReader[0]),
CompanyID = Convert.ToInt32(myReader[1]),
EmployeeID = Convert.ToInt32(myReader[2]),
PersonID = Convert.ToInt32(myReader[3]),
ContractID = Convert.ToInt32(myReader[4]),
PersonName = myReader[5].ToString(),
ContactDate = Convert.ToDateTime(myReader[6]),
ContactTime = Convert.ToDateTime(myReader[7]),
TypeOfContact = myReader[8].ToString(),
ContactMadeBy = myReader[9].ToString(),
ContactDescription = myReader[10].ToString(),
};
listOfContacts.Add(newContact);
}
}
DataTable dTable = new DataTable();
dTable.Columns.Add("ContactID");
dTable.Columns.Add("CompanyID");
dTable.Columns.Add("EmployeeID");
dTable.Columns.Add("PersonID");
dTable.Columns.Add("ContractID");
dTable.Columns.Add("PersonName");
dTable.Columns.Add("ContactDate");
dTable.Columns.Add("ContactTime");
dTable.Columns.Add("TypeOfContact");
dTable.Columns.Add("ContactMadeBy");
dTable.Columns.Add("ContactDescription");
MessageBox.Show(listOfContacts.Count.ToString());
foreach (var contact in listOfContacts)
{
var newRow = dTable.NewRow();
newRow["ContactID"] = contact.ContactID;
newRow["CompanyID"] = contact.CompanyID;
newRow["EmployeeID"] = contact.EmployeeID;
newRow["PersonID"] = contact.PersonID;
newRow["ContractID"] = contact.ContractID;
newRow["PersonName"] = contact.PersonName;
newRow["ContactDate"] = contact.ContactDate;
newRow["ContactTime"] = contact.ContactTime;
newRow["TypeOfContact"] = contact.TypeOfContact;
newRow["ContactMadeBy"] = contact.ContactMadeBy;
newRow["ContactDescription"] = contact.ContactDescription;
}
MessageBox.Show(dTable.Rows.Count.ToString());
You can see the two MessageBox that result in the numbers, am I loading the Data into the DataTable incorrectly?
You have to add the new row to the DataTable:
foreach (var contact in listOfContacts)
{
var newRow = dTable.NewRow();
newRow["ContactID"] = contact.ContactID;
newRow["CompanyID"] = contact.CompanyID;
newRow["EmployeeID"] = contact.EmployeeID;
newRow["PersonID"] = contact.PersonID;
newRow["ContractID"] = contact.ContractID;
newRow["PersonName"] = contact.PersonName;
newRow["ContactDate"] = contact.ContactDate;
newRow["ContactTime"] = contact.ContactTime;
newRow["TypeOfContact"] = contact.TypeOfContact;
newRow["ContactMadeBy"] = contact.ContactMadeBy;
newRow["ContactDescription"] = contact.ContactDescription;
dTable.Rows.Add(newRow); // YOU NEED THIS LINE TO ADD THE NEWROW TO DATATABLE
}
In your foreach loop add this at the end :
dTable.Rows.Add(newRow);

Datagridview horizontal scroll does not go all the way across data

I often run into this problem where when using a datagridview, if I need to make use of a horizontal scroll, it will not go to the end of the form. The last column is then rendered inaccessible. I can usually cheat by extending the size of the dgv or starting the form maximized, but if the vertical scroll works as expected (goes all the way down to the last record in the dataset), why doesn't the horizontal?
private void InitializeMemberGrid()
{
// Set grid properties
this.grdMembers.AutoGenerateColumns = false;
this.grdMembers.RowHeadersVisible = true;
this.grdMembers.Columns.Clear();
mPicWaiting = PartD.Windows.Common.Utility.AddWaitingImage(this.grdMembers);
mPicWaiting.Visible = false;
// Member ID Column
var colMemberID = new DataGridViewTextBoxColumn();
colMemberID.Name = "MemberID";
colMemberID.HeaderText = "Member ID";
colMemberID.DataPropertyName = "ID";
this.grdMembers.Columns.Add(colMemberID);
//// Contract ID Column
var colContractID = new DataGridViewTextBoxColumn();
colContractID.Name = "ContractID";
colContractID.HeaderText = "Contract ID";
colContractID.DataPropertyName = "ContractID";
this.grdMembers.Columns.Add(colContractID);
// SSN Column
var colSSN = new DataGridViewTextBoxColumn();
colSSN.Name = "SSN";
colSSN.HeaderText = "SSN";
colSSN.DataPropertyName = "SSN";
this.grdMembers.Columns.Add(colSSN);
// HICN Column
var colHICN = new DataGridViewTextBoxColumn();
colHICN.Name = "HICN";
colHICN.HeaderText = "HICN";
colHICN.DataPropertyName = "HICN";
this.grdMembers.Columns.Add(colHICN);
// Name Column
var colName = new DataGridViewTextBoxColumn();
colName.Name = "Name";
colName.HeaderText = "Name";
colName.DataPropertyName = "LastNameFirstName";
colName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.grdMembers.Columns.Add(colName);
// DOB Column
var colDOB = new DataGridViewTextBoxColumn();
colDOB.Name = "DOB";
colDOB.HeaderText = "DOB";
colDOB.DataPropertyName = "DateOfBirth";
colDOB.DefaultCellStyle.Format = "MM/dd/yyyy";
this.grdMembers.Columns.Add(colDOB);
// Retirement Date Column
var colRetireDate = new DataGridViewTextBoxColumn();
colRetireDate.Name = "RetireDate";
colRetireDate.HeaderText = "Retirement";
colRetireDate.DataPropertyName = "RetireDate";
this.grdMembers.Columns.Add(colRetireDate);
// RelCode Column
var colRelCode = new DataGridViewTextBoxColumn();
colRelCode.Name = "RelCode";
colRelCode.HeaderText = "Rel";
colRelCode.DataPropertyName = "RelCode";
this.grdMembers.Columns.Add(colRelCode);
// Resend Column
var colResend = new DataGridViewTextBoxColumn();
colResend.Name = "Resend";
colResend.HeaderText = "Resend";
colResend.DataPropertyName = "Resend";
this.grdMembers.Columns.Add(colResend);
// Sent Column
var colSent = new DataGridViewTextBoxColumn();
colSent.Name = "Sent";
colSent.HeaderText = "Sent";
colSent.DataPropertyName = "SubmissionCount";
this.grdMembers.Columns.Add(colSent);
// Status Column
var colStatus = new DataGridViewTextBoxColumn();
colStatus.Name = "Status";
colStatus.HeaderText = "Status";
colStatus.DataPropertyName = "Status";
this.grdMembers.Columns.Add(colStatus);
}
You have probably set the width of the DataGridView instead of docking the control within the form.
Make sure the control looks right in the designer and then anchor it on the right hand side. This will stop the end column being chopped off if the form is resized. Better still, add a panel to embed your control in and dock it accordingly.
I hope this helps.
Setting the last column's "AutoSizeMode" property to "AllCells" fixed it for me:
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

Categories