I am creating grid view through data adapter and all columns and rows are created from data base but problem occurs that when rows all rows are created there comes another empty row i want to stop that row to be generated and when i click and some value in that extra row another new row is created i want to stop all extra rows how to do this any help???
this is the grid view code i am using
conn.ConnectionString = s;
conn.Open();
dAdapter = new SqlDataAdapter(query, s);
dTable = new DataTable();
DataView myDataView = dTable.DefaultView;
dAdapter.Fill(dTable);
BindingSource bndSource = new BindingSource();
bndSource.DataSource = dTable;
dataGrid.DataSource = bndSource;
dataGrid.Columns["StudentId"].ReadOnly = true;
dataGrid.Columns["StudentName"].ReadOnly = true;
conn.Close();
Try setting AllowUserToAddRows to false.
Related
I generate an Excel sheet which contains data formatted like so:
IOW, the "Total Packages", "Total Purchases", "Average Price", and "% of Total" values are located in a column of their own (Data) for each overarching (or sidearching) description.
When I PivotTablize this data, it places these values beneath each description:
This makes sense, but those accustomed to the previous appearance want it to be replicated in the PivotTable. How can I shift the Description "subitems" in the PivotTable to their own column?
This is the code I use to generate the PivotTable:
private void PopulatePivotTableSheet()
{
string NORTHWEST_CORNER_OF_PIVOT_TABLE = "A6";
AddPrePivotTableDataToPivotTableSheet();
var dataRange = rawDataWorksheet.Cells[rawDataWorksheet.Dimension.Address];
dataRange.AutoFitColumns();
var pivotTable = pivotTableWorksheet.PivotTables.Add(
pivotTableWorksheet.Cells[NORTHWEST_CORNER_OF_PIVOT_TABLE],
dataRange,
"PivotTable");
pivotTable.MultipleFieldFilters = true;
pivotTable.GridDropZones = false;
pivotTable.Outline = false;
pivotTable.OutlineData = false;
pivotTable.ShowError = true;
pivotTable.ErrorCaption = "[error]";
pivotTable.ShowHeaders = true;
pivotTable.UseAutoFormatting = true;
pivotTable.ApplyWidthHeightFormats = true;
pivotTable.ShowDrill = true;
// Row field[s]
var descRowField = pivotTable.Fields["Description"];
pivotTable.RowFields.Add(descRowField);
// Column field[s]
var monthYrColField = pivotTable.Fields["MonthYr"];
pivotTable.ColumnFields.Add(monthYrColField);
// Data field[s]
var totQtyField = pivotTable.Fields["TotalQty"];
pivotTable.DataFields.Add(totQtyField);
var totPriceField = pivotTable.Fields["TotalPrice"];
pivotTable.DataFields.Add(totPriceField);
// Don't know how to calc these vals here, so have to grab them from the source data sheet
var avgPriceField = pivotTable.Fields["AvgPrice"];
pivotTable.DataFields.Add(avgPriceField);
var prcntgOfTotalField = pivotTable.Fields["PrcntgOfTotal"];
pivotTable.DataFields.Add(prcntgOfTotalField);
}
So there is one RowField ("MonthYr") with values such as "201509" and "201510", one ColumnField ("Description") and four DataFields, which align themseles under the Description column field. I want to shift those four fields to the right, to their own column, and the Description label to be vertically centered between those four values to their left. [How] is this possible?
Try changing the layout of your table with
pivotTable.RowAxisLayout xlTabularRow
pivotTable.MergeLabels = True
this is the result:
A little script in C# with Interop.Excel. Included the using ;)
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
var excelApp = new Excel.Application();
Excel.Workbook wb = excelApp.Workbooks.Open(#"e:\42\TestSO.xlsx");
Worksheet ws = wb.Worksheets["SheetName"];
PivotTable pt = ws.PivotTables("DynamicTableName");
pt.RowAxisLayout(XlLayoutRowType.xlTabularRow);
pt.MergeLabels = true;
wb.Save();
wb.Close();
Marshal.ReleaseComObject(ws);
It's all about PivotTable layout / design... here's the manual way - Salvador has the VBA way :)...
Is there a way in MigraDoc to make an entire table cell a link? I have a tabular table of contents, and the page number is difficult to click. I would prefer if the entire cell was clickable to navigate to a specified page. Here is an example of my code:
// Create the table within the document
var document = new Document();
var section = document.AddSection();
var table = section.AddTable();
// Create a column in the table
var column = table.AddColumn();
column.Width = "2cm";
// Create a row in the table
var row = table.AddRow();
row.Height = "1cm";
// Add a hyperlink to the appropriate page
var paragraph = row.Cells[0].AddParagraph();
var hyperlink = paragraph.AddHyperlink("MyBookmarkName");
hyperlink.AddPageRefField("MyBookmarkName");
...
// Create the bookmark later in the document
I'm afraid there is no easy way to make the whole cell clickable. I haven't tried it myself, but you can add images (visible or transparent) or text to the hyperlink.
This will make the clickable area bigger - and if you use e.g. blue underlined text there will be a visual hint that the text is clickable.
I was inspired by the answer from the PDFsharp Team to try and fill the cell with a blank hyperlink image, with text over the hyperlink. Since my ultimate goal was to actually make an entire row a hyperlink, I came up with the following solution.
First, add an additional zero-width column prior to the first column in the table that you want to be a hyperlink. Next, add a paragraph, hyperlink, and transparent 1-pixel image to each zero-width cell. Specify the image height and width to fill however many table cells you want to be a link. Also, be sure to set the font size of the paragraph containing the link to nearly zero (zero throws an exception, but images are aligned on the font baseline, so you need a very small number to prevent the paragraph from being larger than the image).
Note that a zero-width column, even with borders, does not change the apparent border width when viewing the resulting PDF. The following code illustrates my approach:
// Declare some constants
var _rowHeight = new Unit(.75, UnitType.Centimeter);
// Create the document, section, and table
var document = new Document();
var section = document.AddSection();
var table = section.AddTable();
// Format the table
table.Rows.Height = _rowHeight;
table.Rows.VerticalAlignment = VerticalAlignment.Center;
// Define the column titles and widths
var columnInfos = new[] {
new { Title = "Non-Link Column", Width = new Unit(8, UnitType.Centimeter) },
new { Title = "" , Width = new Unit(0 ) },
new { Title = "Link Column 1" , Width = new Unit(8, UnitType.Centimeter) },
new { Title = "Link Column 2" , Width = new Unit(8, UnitType.Centimeter) },
};
// Define the column indices
const int colNonLink = 0;
const int colHyperlink = 1;
const int colLink1 = 2;
const int colLink2 = 3;
// Create all of the table columns
Unit tableWidth = 0;
foreach (var columnInfo in columnInfos)
{
table.AddColumn(columnInfo.Width);
tableWidth += columnInfo.Width;
}
// Remove the padding on the link column
var linkColumn = table.Columns[colHyperlink];
linkColumn.LeftPadding = 0;
linkColumn.RightPadding = 0;
// Compute the width of the summary links
var linkWidth = tableWidth -
columnInfos.Take(colHyperlink).Sum(ci => ci.Width);
// Create a row to store the column headers
var headerRow = table.AddRow();
headerRow.Height = ".6cm";
headerRow.HeadingFormat = true;
headerRow.Format.Font.Bold = true;
// Populate the header row
for (var colIdx = 0; colIdx < columnInfos.Length; ++colIdx)
{
var columnTitle = columnInfos[colIdx].Title;
if (!string.IsNullOrWhiteSpace(columnTitle))
{
headerRow.Cells[colIdx].AddParagraph(columnTitle);
}
}
// In the real code, the following is done in a loop to dynamically add rows
var row = table.AddRow();
// Populate the row header
row.Cells[colNonLink].AddParagraph("Not part of link");
// Change the alignment of the link cell
var linkCell = row.Cells[colHyperlink];
linkCell.VerticalAlignment = VerticalAlignment.Top;
// Add a hyperlink that fills the remaining cells in the row
var linkParagraph = linkCell.AddParagraph();
linkParagraph.Format.Font.Size = new Unit(.001, UnitType.Point);
var hyperlink = linkParagraph.AddHyperlink("MyBookmarkName");
var linkImage = hyperlink.AddImage("Transparent.gif");
linkImage.Height = _rowHeight;
linkImage.Width = linkWidth;
// Populate the remaining two cells
row.Cells[colLink1].AddParagraph("Part of link 1");
row.Cells[colLink2].AddParagraph("Part of link 2");
// Add a border around the cells
table.SetEdge(0, 0, columnInfos.Length, table.Rows.Count,
Edge.Box | Edge.Interior, BorderStyle.Single, .75, Colors.Black);
The result of the above code is a document containing a table with 2 rows, 3 visible columns, where the entirety of the last two cells in the final row are a hyperlink to "MyBookmarkName". Just for reference, I did modify the PDFSharp source code according to the advice here to remove borders around hyperlinks, which looked wonky at certain zoom levels in Adobe Acrobat Reader.
I have a datatable problem when I reject changes on the table. I've created an example below which demonstrates the problem:
DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Last_Name", typeof(string));
table.Columns.Add("Male", typeof(Boolean));
foreach (DataColumn column in table.Columns)
{
if (column.ColumnName == "Name")
{
column.Unique = true;
}
}
DataRow row;
row = table.NewRow();
row["Name"] = String.Format("Steve");
row["Last_Name"] = String.Format("Smith");
row["Male"] = true;
table.Rows.Add(row);
table.AcceptChanges();
So at this stage I have a DataTable with a unique column constraint and 1 row in that table.
I now delete that row:
row.Delete();
This sets the rowstate to Deleted.
At this stage I realise that I've made a mistake and want to add the row again. So I create the new row again and add it to the DataTable:
row = table.NewRow();
row["Name"] = String.Format("Steve");
row["Last_Name"] = String.Format("Smith");
row["Male"] = true;
table.Rows.Add(row);
At this stage my DataTable contents are in the following state:
table.Rows[0].RowState is Deleted
table.Rows[1].RowState is Added
Now, I've changed my mind about the whole thing and want to get back to how I started so I call RejectChanges:
table.RejectChanges();
When I do this I receive the following error:
Column 'Name' is constrained to be unique. Value 'Steve' is already present.
I understand that there are 2 rows with the same values but I thought reject changes would have ingored this as the RowStates are different.
Any ideas how I can get round this?
In my live code I use this to move rows between to 2 grids (like allowing the user to selected what columns are visible)
I'm using C#4.0 in Visual Studio 2012
Thanks in advance
I want to delete row from datagridview when user clicks the delete button.The datagridview bounded to datatable _dt so i remove the row from _dt and try to rebind the modified _dt to datagridview but instead of deleting the row gets added to the last row of the datagridview what am I doing wrong here
private void btnDelete_Click(object sender, EventArgs e)
{
if (dataGridView1 != null && dataGridView1.SelectedRows.Count == 1)
{
string key = dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString();
DataColumn[] keyColumns = new DataColumn[1];
keyColumns[0] = _dt.Columns["ID"];
_dt.PrimaryKey = keyColumns;
rowToDelete = _dt.Rows.Find(key);
_dt.Rows.Remove(rowToDelete);
_dt.AcceptChanges();
SqlCommandBuilder cb = new SqlCommandBuilder(_sqlDa);
_sqlDa.Fill(_dt);
_sqlDa.Update(_dt);
dataGridView1.DataSource = null;
dataGridView1.DataSource = _dt;
}
}
No need for Fill before update and also delete this row
_dt.AcceptChanges();
because this will remove the row from memory and when you call update
only the remaining rows are updated, it will not delete the row from database.
No need to call Fill Before Update, because Fill will get data again from db and your changes will be lost. So This will work for you.
SqlCommandBuilder cb = new SqlCommandBuilder(_sqlDa);
//_sqlDa.Fill(_dt);
_sqlDa.Update(_dt);
I need to select the last row in DataGridView, when form loads the first time. So
I wrote this code in Form_Load event :
da.SelectCommand = new SqlCommand("SELECT * FROM Days", cn);
ds.Clear();
da.Fill(ds);
dataGridView1.DataSource = dsD.Tables[0];
dataGridView1.ClearSelection();
int nRowIndex = dataGridView1.Rows.Count - 1;
dataGridView1.Rows[nRowIndex].Selected = true;
dataGridView1.FirstDisplayedScrollingRowIndex = nRowIndex;
dataGridView1.Refresh();
But this isnĀ“t doing anything. It still selects the first row, but this code works when I save the data in the database and then fill the dataset. But why not the first time when I load the form.
I used :
dataGridView1.CurrentCell = dataGridView1.Rows[nRowIndex].Cells[0];
and it worked.