Android: Passing Checked items from a ListView to another activity with a ListView - android-studio

I am trying to pass checked items from one listview to another listview in a separate activity. Ideally, the user would click all of the items they wanted, then click a button; then, the button would take all of the items from the rows clicked to the new activity. The problem that I keep having is when I click on the row; all of the information shows up on the next activity instead of the individual rows there were selected.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapterTwo.setCheckBox(position);
adapterTwo.notifyDataSetChanged();
}
});
practiceFinal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String entry = "";
String judge ="";
Integer points = 0;
Integer work = 0;
Integer design = 0;
Integer doc = 0;
Integer pres= 0;
Integer safety= 0;
Integer diff = 0;
String ribbon ="";
Intent intent = new Intent(CSS.this, FinalCSS.class);
for (Team hold: adapterTwo.getTeamArrayList())
{
if (hold.isChecked())
{
}
else
{
entry += " "+ hold.getEntryNumber();
judge += hold.getTeamJudgeNumber();
points+= hold.getTotalPoints();
work+= hold.getWorkmanship();
design += hold.getDesign();
doc += hold.getDocumnetation();
pres+= hold.getPresentation();
safety += hold.getSafety();
diff += hold.getDifficulty();
ribbon += hold.getRibbon();
intent.putExtra( "KeyEntry", entry);
intent.putExtra("KeyJudge", judge);
intent.putExtra("KeyPoints", points);
intent.putExtra("KeyWork", work);
intent.putExtra("KeyDesign", design);
intent.putExtra("KeyDoc",doc);
intent.putExtra("KeyPres", pres);
intent.putExtra("KeySafety", safety);
intent.putExtra("KeyRibbon", ribbon);
intent.putExtra("KeyDiff", diff);
}
}
startActivity(intent);
}
});
listView = findViewById(R.id.listViewFinal);
teamsList= new ArrayList<>();
String entry = getIntent().getStringExtra("KeyEntry");
String judge=getIntent().getStringExtra("KeyJudge");
Integer points= getIntent().getIntExtra("KeyPoints",0);
Integer workmanship=getIntent().getIntExtra("KeyWork",0);
Integer design=getIntent().getIntExtra("KeyDesign",0);
Integer documentation =getIntent().getIntExtra("KeyDoc",0);
Integer pres = getIntent().getIntExtra("KeyPres",0);
Integer difficulty =getIntent().getIntExtra("KeyDiff",0);
Integer safety =getIntent().getIntExtra("KeySafety",0);
String ribbon= getIntent().getStringExtra("KeyRibbon");
Team teams = null;
teams = new Team(judge,entry,points, workmanship,design,documentation,pres,difficulty,safety,ribbon,true);
teamsList.add(teams);
Team teamsT = null;
teamsT = new Team(judge,entry,points, workmanship,design,documentation,pres,difficulty,safety,ribbon,true);
teamsList.add(teamsT);
TeamAdapterTwo adapterTwo = new TeamAdapterTwo(FinalCSS.this, teamsList);
listView.setAdapter(adapterTwo);
Second ActivityFirst ActivitySecond Activity

You are concatenate the information on a global variable. Thus, if we trace the points attribute evolution, we have:
points = 0
points += 1 (points = 1)
points += 2 (points = 3)
points += 3 (points = 6)
points += 4 (points = 10)
Moreover, intent.putExtra erase the old value associated to a key, so at each iteration of the loop, you are replacing the old value of points by the new one. Therefore, at the end, you will give points = 10 to the second Activity.
You have two options:
Create a unique key for each hold but it will not be easy for the second Activity to know this unique key.
Instead of put an integer as extra, put an array of integers (I recommend this way)
However, you seem to have an other issue because the final value of points is the sum of all lines rather than the sum of the checked ones.

Related

vaadin table vertically till but not beyond the bottom of the page, scrollbars as needed

In my vaadin 7 application I have a CSSLayout that contains a Tabsheet. The Tabsheet contains a horizontalLayout. The HorizontalLayout contains a Table.
The table have a varying number of columns (between 3 and 20, changes upon request).
I want this table to occupy all available space both horizontally and vertically.
Vertically however the table should not extend beyond the the screen. So in case of having more rows than it can display the table should have a vertical scrollbar. (That is the case if I set the number of rows in table.setPageLength(), however I want to achieve this without setting explicit rownumbers, because I want the table to occupy all available space regardless of screensize, etc...)
Horizontally I also want a scrollbar if there are more columns then we have space for.
If I leave everything (csslayout, tabsheet, horizontallayout, table) default, I get the scrollbars, but I get a lot of space unused.
If I use setSizeFull() on tabsheet, horizontallayout, table then I get no unused space, however I lose the horizontal scrollbar and I can't ever reach end of the table with the vertical scrollbar.
Any help is appreciated.
EDIT -- UPDATE -- EDIT -- UPDATE --EDIT -- UPDATE --EDIT -- UPDATE
Here is a sample code. On my screen it's impossible to scroll down to the last row of the table. (and equally impossible to use the horizontal scrollbar)
#Override
protected void init(#SuppressWarnings("unused") VaadinRequest request) {
CssLayout css = new CssLayout();
HorizontalLayout upper = new HorizontalLayout();
OptionGroup first = new OptionGroup();
first.addItem("AAA");
first.addItem("BBB");
first.addItem("CCC");
first.addItem("DDD");
first.addItem("EEE");
first.addItem("Whatever");
upper.addComponent(first);
css.addComponent(upper);
HorizontalLayout hl = new HorizontalLayout();
hl.setMargin(true);
hl.setSpacing(true);
IndexedContainer c = new IndexedContainer();
for (int i = 0; i < 40; i++)
c.addContainerProperty("name" + i, String.class, "name" + i);
Table table = new Table("Test table", c);
for (int i = 0; i < 100; i++) {
Integer id = (Integer) c.addItem();
c.getItem(id).getItemProperty("name0").setValue(String.valueOf(i));
}
hl.addComponent(table);
TabSheet tab = new TabSheet();
tab.addTab(hl, "Table");
css.addComponent(tab);
hl.setSizeFull();
table.setSizeFull();
tab.setSizeFull();
css.setSizeFull();
setContent(css);
}
Maybe you don't set the size full on the css layout or maybe there are some trouble with styles.
It's better posting some code in questions like Why my code dosen't work?. However I wrote a simple test following your description and work as expected.
Edit
Try with VerticalLayout instead CssLayout
public class TestTableApp extends UI {
#Override
protected void init(VaadinRequest request) {
VerticalLayout css = new VerticalLayout();
HorizontalLayout upper = new HorizontalLayout();
OptionGroup first = new OptionGroup();
first.addItem("AAA");
first.addItem("BBB");
first.addItem("CCC");
first.addItem("DDD");
first.addItem("EEE");
first.addItem("Whatever");
upper.addComponent(first);
css.addComponent(upper);
HorizontalLayout hl = new HorizontalLayout();
hl.setMargin(true);
hl.setSpacing(true);
IndexedContainer c = new IndexedContainer();
for (int i = 0; i < 40; i++)
c.addContainerProperty("name" + i, String.class, "name" + i);
Table table = new Table("Test table", c);
for (int i = 0; i < 100; i++) {
Integer id = (Integer) c.addItem();
c.getItem(id).getItemProperty("name0").setValue(String.valueOf(i));
}
hl.addComponent(table);
TabSheet tab = new TabSheet();
tab.addTab(hl, "Table");
css.addComponent(tab);
hl.setSizeFull();
tab.setSizeFull();
table.setSizeFull();
css.setSizeFull();
// this do the trick
css.setExpandRatio(upper, 0);
css.setExpandRatio(tab, 1);
setContent(css);
}
}

How to Multiply Data Gridview two columns and show the result in another column

I have a gridview (Order) with three columns:
Price
Quantity
Total
I want to multiply Price with Quantity and show the result in Total column of dataGridview.
Remember: my dataGridview isn't bind with any table.
I am trying this code to achieve my goal but this isn't working means value isn't being returned:
private void totalcal()
{
// is the foreach condition true? Remember my gridview isn't bound to any tbl
foreach (DataGridViewRow row in gvSale.Rows)
{
int a = Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value); // value is null why??
row.Cells[5].Value = a;
}
}
This is the method which I am calling on a button click. (It is not working reason define inside of my code above)
And plus I want to know which is the suitable Datagridview event for this calculation?? I don't want to calculate the total on button click
try
int.Parse(row.Cells[3].Value.toString()) * int.Parse(row.Cells[4].Value.toString())
insted of
Convert.ToInt32(row.Cells[3].Value) * Convert.ToInt32(row.Cells[4].Value)
And you know you can call this method anytime, if you dont want it to be with button click. Call it after gvSale's row populating operations finished.
EDIT
I guess you want the calculations to be done while the user is entering Price or Quanitity. For that you need to write a EditingControlShowing method for your datagridview. Here's a piece of code. I tested it actually and got it working.
Add this code in your main class definition after InitializeComponent(); line
gvSale.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.gvSale_EditingControlShowing);
And then add this methods :
TextBox tb = new TextBox(); // this is just a textbox to use in editing control
int Price_Index = 3; // set this to your Price Column Index
int Quantity_Index = 4; // set this to your Quantity Column Index
int Total_Index = 5; // set this to your Total Column Index
private void gvSale_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (gvSale.CurrentCell.ColumnIndex == Price_Index || gvSale.CurrentCell.ColumnIndex == Quantity_Index)
{
tb = e.Control as TextBox;
tb.KeyUp += new KeyEventHandler(Calculate_Total);
}
}
private void Calculate_Total(object sender, KeyEventArgs e)
{
int Price_Value = 0;
int Quantity_Value = 0;
int.TryParse(gvSale.CurrentCell.ColumnIndex != Price_Index ? gvSale.CurrentRow.Cells[Price_Index].Value.ToString() : tb.Text, out Price_Value);
int.TryParse(gvSale.CurrentCell.ColumnIndex != Quantity_Index ? gvSale.CurrentRow.Cells[Quantity_Index].Value.ToString() : tb.Text, out Quantity_Value);
gvSale.CurrentRow.Cells[Total_Index].Value = Price_Value * Quantity_Value;
}

Count the number of frequency for different characters in a string

i am currently tried to create a small program were the user enter a string in a text area, clicks on a button and the program counts the frequency of different characters in the string and shows the result on another text area.
E.g. Step 1:- User enter:- aaabbbbbbcccdd
Step 2:- User click the button
Step 3:- a 3
b 6
c 3
d 1
This is what I've done so far....
public partial class Form1 : Form
{
Dictionary<string, int> dic = new Dictionary<string, int>();
string s = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
s = textBox1.Text;
int count = 0;
for (int i = 0; i < s.Length; i++ )
{
textBox2.Text = Convert.ToString(s[i]);
if (dic.Equals(s[i]))
{
count++;
}
else
{
dic.Add(Convert.ToString(s[i]), count++);
}
}
}
}
}
Any ideas or help how can I countinue because till now the program is giving a run time error when there are same charachter!!
Thank You
var lettersAndCounts = s.GroupBy(c=>c).Select(group => new {
Letter= group.Key,
Count = group.Count()
});
Instead of dic.Equals use dic.ContainsKey. However, i would use this little linq query:
Dictionary<string, int> dict = textBox1.Text
.GroupBy(c => c)
.ToDictionary(g => g.Key.ToString(), g => g.Count());
You are attempting to compare the entire dictionary to a string, that doesn't tell you if there is a key in the dictionary that corresponds to the string. As the dictionary never is equal to the string, your code will always think that it should add a new item even if one already exists, and that is the cause of the runtime error.
Use the ContainsKey method to check if the string exists as a key in the dictionary.
Instead of using a variable count, you would want to increase the numbers in the dictionary, and initialise new items with a count of one:
string key = s[i].ToString();
textBox2.Text = key;
if (dic.ContainsKey(key)) {
dic[key]++;
} else {
dic.Add(key, 1);
}
I'm going to suggest a different and somewhat simpler approach for doing this. Assuming you are using English strings, you can create an array with capacity = 26. Then depending on the character you encounter you would increment the appropriate index in the array. For example, if the character is 'a' increment count at index 0, if the character is 'b' increment the count at index 1, etc...
Your implementation will look something like this:
int count[] = new int [26] {0};
for(int i = 0; i < s.length; i++)
{
count[Char.ToLower(s[i]) - int('a')]++;
}
When this finishes you will have the number of 'a's in count[0] and the number of 'z's in count[25].

Epplus SetPosition picture issue

I am using Epplus library to generate Excel 2010 and up compatible files in Asp.Net C#.
I am using version 3.1.2 which is the latest at this moment.
I am setting the row height first, before adding any pictures like this:
ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("sheet 1");
while (i < dt.Rows.Count + offset)
{
ws.Row(i).Height = 84;
i++;
}
dt is my DataTable with DataRows.
After setting the height, I am looping again through the rows to add the pictures
while (i < dt.Rows.Count + offset)
{
var prodImg = ws.Drawings.AddPicture(dr["code"].ToString(), new FileInfo(path));
prodImg.SetPosition(i - 1, 0, 14, 0);
prodImg.SetSize(75);
}
This works, but this does not:
var prodImg = ws.Drawings.AddPicture(dr["code"].ToString(), new FileInfo(path));
int w = prodImg.Image.Width;
int h = prodImg.Image.Height;
if (h > 140) // because height of 84 is 140 pixels in excel
{
double scale = h / 140.0;
w = (int)Math.Floor(w / scale);
h = 140;
}
int xOff = (150 - w) / 2;
int yOff = (140 - h) / 2;
prodImg.SetPosition(i - 1, xOff, 11, yOff);
prodImg.SetSize(w, h);
This results in off center pictures and unresized images. And this code then which is in the same loop:
var prodImgDm = ws.Drawings.AddPicture("bcdm" + dr["code"].ToString(), new FileInfo(pathDm));
prodImgDm.SetPosition(i - 1, 25, 15, 40);
prodImgDm.SetSize(100);
This does work sometimes. the pictures prodImgDm are datamatrix images with a static width and height and do not need to be resized because they are always small/tiny. So also without the SetSize in some rows, it works and in some other rows, it does not work. Really strange because the code is the same. It might be something in the library and/or Excel. Perhaps I am using it wrong? Any epplus picture expert?
Thanks in advance!!
edit sometimes a picture is worth a thousand words, so here is the screenshot. As you can see the product images are not horizontal and vertical aligned in the cell. And the datamatrix on the far right is sometimes scaled about 120% even when I set SetSize(100) so it is really strange to me. So the last datamatrix has the correct size... I already found this SO thread but that does not help me out, I think.
edit 2013/04/09 Essenpillai gave me a hint to set
pck.DoAdjustDrawings = false;
but that gave me even stranger images:
the datamatrix is still changing on row basis. on row is ok, the other is not. and the ean13 code is too wide.
public static void CreatePicture(ExcelWorksheet worksheet, string name, Image image, int firstColumn, int lastColumn, int firstRow, int lastRow, int defaultOffsetPixels)
{
int columnWidth = GetWidthInPixels(worksheet.Cells[firstRow, firstColumn]);
int rowHeight = GetHeightInPixels(worksheet.Cells[firstRow, firstColumn]);
int totalColumnWidth = columnWidth * (lastColumn - firstColumn + 1);
int totalRowHeight = rowHeight * (lastRow - firstRow + 1);
double cellAspectRatio = Convert.ToDouble(totalColumnWidth) / Convert.ToDouble(totalRowHeight);
int imageWidth = image.Width;
int imageHeight = image.Height;
double imageAspectRatio = Convert.ToDouble(imageWidth) / Convert.ToDouble(imageHeight);
int pixelWidth;
int pixelHeight;
if (imageAspectRatio > cellAspectRatio)
{
pixelWidth = totalColumnWidth - defaultOffsetPixels * 2;
pixelHeight = pixelWidth * imageHeight / imageWidth;
}
else
{
pixelHeight = totalRowHeight - defaultOffsetPixels * 2;
pixelWidth = pixelHeight * imageWidth / imageHeight;
}
int rowOffsetPixels = (totalRowHeight - pixelHeight) / 2;
int columnOffsetPixels = (totalColumnWidth - pixelWidth) / 2;
int rowOffsetCount = 0;
int columnOffsetCount = 0;
if (rowOffsetPixels > rowHeight)
{
rowOffsetCount = (int)Math.Floor(Convert.ToDouble(rowOffsetPixels) / Convert.ToDouble(rowHeight));
rowOffsetPixels -= rowHeight * rowOffsetCount;
}
if (columnOffsetPixels > columnWidth)
{
columnOffsetCount = (int)Math.Floor(Convert.ToDouble(columnOffsetPixels) / Convert.ToDouble(columnWidth));
columnOffsetPixels -= columnWidth * columnOffsetCount;
}
int row = firstRow + rowOffsetCount - 1;
int column = firstColumn + columnOffsetCount - 1;
ExcelPicture pic = worksheet.Drawings.AddPicture(name, image);
pic.SetPosition(row, rowOffsetPixels, column, columnOffsetPixels);
pic.SetSize(pixelWidth, pixelHeight);
}
public static int GetHeightInPixels(ExcelRange cell)
{
using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
{
float dpiY = graphics.DpiY;
return (int)(cell.Worksheet.Row(cell.Start.Row).Height * (1 / 72.0) * dpiY);
}
}
public static float MeasureString(string s, Font font)
{
using (var g = Graphics.FromHwnd(IntPtr.Zero))
{
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
return g.MeasureString(s, font, int.MaxValue, StringFormat.GenericTypographic).Width;
}
}
public static int GetWidthInPixels(ExcelRange cell)
{
double columnWidth = cell.Worksheet.Column(cell.Start.Column).Width;
Font font = new Font(cell.Style.Font.Name, cell.Style.Font.Size, FontStyle.Regular);
double pxBaseline = Math.Round(MeasureString("1234567890", font) / 10);
return (int)(columnWidth * pxBaseline);
}
enter image description here
I have the same problem with Epplus library.
After I find no solution how to solve this in my code, I checked source code of this library.
Epplus create excel picture always as twoCellAnchor drawing. In xlsx files you can find drawingXYZ.xml with this code:
<xdr:twoCellAnchor editAs="oneCell">
<xdr:from> ... </xdr:from>
<xdr:to> ... </xdr:to>
<xdr:pic>
...
</xdr:twoCellAnchor>
So, picture is always connected to two cells, and this is not variable part of Epplus library. You can find this part of code in ExcelDrawing.cs file.
XmlElement drawNode = _drawingsXml.CreateElement(
"xdr", "twoCellAnchor", ExcelPackage.schemaSheetDrawings);
colNode.AppendChild(drawNode);
You can easy create your own copy of this dll. The good news is that you need to modify only two files to fix this problem. So..
Download your copy of source codes for Epplus library from this site and open in Visual Studio.
We need to generate code of drawing as oneCellAnchor, so we must remove <xdr:to> element for pictures and create element <xdr:ext /> with picture dimensions as parameters.
New xml structure will looks like:
<xdr:oneCellAnchor editAs="oneCell">
<xdr:from> ... </xdr:from>
<xdr:ext cx="1234567" cy="7654321" />
<xdr:pic>
...
</xdr:oneCellAnchor>
Ok, so, how to do this?
Changes in Epplus code
ExcelDrawings.cs (link to file here)
At first we modify method CreateDrawingXml() inside ExcelDrawings.cs. Order to preserve the original functionality we add an optional parameter (if create oneCellAnchor) with default value. And in method, based this parameter, we create one or tow cell anchor and create or not <xdr:to> element.
Important part of this method code:
private XmlElement CreateDrawingXml(bool twoCell = true) {
if (DrawingXml.OuterXml == "")
{ ... } // not changed
XmlNode colNode= _drawingsXml.SelectSingleNode("//xdr:wsDr", NameSpaceManager);
//First change in method code
XmlElement drawNode;
if (twoCell)
drawNode = _drawingsXml.CreateElement(
"xdr", "twoCellAnchor", ExcelPackage.schemaSheetDrawings);
else
drawNode = _drawingsXml.CreateElement(
"xdr", "oneCellAnchor", ExcelPackage.schemaSheetDrawings);
colNode.AppendChild(drawNode);
//Add from position Element; // Not changed
XmlElement fromNode = _drawingsXml.CreateElement(
"xdr", "from", ExcelPackage.schemaSheetDrawings);
drawNode.AppendChild(fromNode);
fromNode.InnerXml = "<xdr:col>0</xdr:col><xdr:colOff>0</xdr:colOff>"
+ "<xdr:row>0</xdr:row><xdr:rowOff>0</xdr:rowOff>";
//Add to position Element;
//Second change in method
if (twoCell)
{
XmlElement toNode = _drawingsXml.CreateElement(
"xdr", "to", ExcelPackage.schemaSheetDrawings);
drawNode.AppendChild(toNode);
toNode.InnerXml = "<xdr:col>10</xdr:col><xdr:colOff>0</xdr:colOff>"
+ "<xdr:row>10</xdr:row><xdr:rowOff>0</xdr:rowOff>";
}
return drawNode;
}
Then we modify two methods for AddPicture inside the same file:
public ExcelPicture AddPicture(string Name, Image image, Uri Hyperlink)
{
if (image != null) {
if (_drawingNames.ContainsKey(Name.ToLower())) {
throw new Exception("Name already exists in the drawings collection");
}
XmlElement drawNode = CreateDrawingXml(false);
// Change: we need create element with dimensions
// like: <xdr:ext cx="3857625" cy="1047750" />
XmlElement xdrext = _drawingsXml.CreateElement(
"xdr", "ext", ExcelPackage.schemaSheetDrawings);
xdrext.SetAttribute("cx",
(image.Width * ExcelDrawing.EMU_PER_PIXEL).ToString());
xdrext.SetAttribute("cy",
(image.Height * ExcelDrawing.EMU_PER_PIXEL).ToString());
drawNode.AppendChild(xdrext);
// End of change, next part of method is the same:
drawNode.SetAttribute("editAs", "oneCell");
...
}
}
And this method with FileInfo as input parameter:
public ExcelPicture AddPicture(string Name, FileInfo ImageFile, Uri Hyperlink)
{
if (ImageFile != null) {
if (_drawingNames.ContainsKey(Name.ToLower())) {
throw new Exception("Name already exists in the drawings collection");
}
XmlElement drawNode = CreateDrawingXml(false);
// Change: First create ExcelPicture object and calculate EMU dimensions
ExcelPicture pic = new ExcelPicture(this, drawNode, ImageFile, Hyperlink);
XmlElement xdrext = _drawingsXml.CreateElement(
"xdr", "ext", ExcelPackage.schemaSheetDrawings);
xdrext.SetAttribute("cx",
(pic.Image.Width * ExcelDrawing.EMU_PER_PIXEL).ToString());
xdrext.SetAttribute("cy",
(pic.Image.Height * ExcelDrawing.EMU_PER_PIXEL).ToString());
drawNode.AppendChild(xdrext);
// End of change, next part of method is the same (without create pic object)
drawNode.SetAttribute("editAs", "oneCell");
...
}
}
So, this are all important code. Now we must change code for searching nodes and preserve order in elements.
In private void AddDrawings() we change xpath from:
XmlNodeList list = _drawingsXml.SelectNodes(
"//xdr:twoCellAnchor", NameSpaceManager);
To this:
XmlNodeList list = _drawingsXml.SelectNodes(
"//(xdr:twoCellAnchor or xdr:oneCellAnchor)", NameSpaceManager);
It is all in this file, now we change
ExcelPicture.cs (link to file here)
Original code find node for append next code in constructor like this:
node.SelectSingleNode("xdr:to",NameSpaceManager);
Because we do not create <xdr:to> element always, we change this code:
internal ExcelPicture(ExcelDrawings drawings, XmlNode node
, Image image, Uri hyperlink)
: base(drawings, node, "xdr:pic/xdr:nvPicPr/xdr:cNvPr/#name")
{
XmlElement picNode = node.OwnerDocument.CreateElement(
"xdr", "pic", ExcelPackage.schemaSheetDrawings);
// Edited: find xdr:to, or xdr:ext if xdr:to not exists
XmlNode befor = node.SelectSingleNode("xdr:to",NameSpaceManager);
if (befor != null && befor.Name == "xdr:to")
node.InsertAfter(picNode, befor);
else {
befor = node.SelectSingleNode("xdr:ext", NameSpaceManager);
node.InsertAfter(picNode, befor);
}
// End of change, next part of constructor is unchanged
_hyperlink = hyperlink;
...
}
And the same for second constructor with FileInfo as input parameter:
internal ExcelPicture(ExcelDrawings drawings, XmlNode node
, FileInfo imageFile, Uri hyperlink)
: base(drawings, node, "xdr:pic/xdr:nvPicPr/xdr:cNvPr/#name")
{
XmlElement picNode = node.OwnerDocument.CreateElement(
"xdr", "pic", ExcelPackage.schemaSheetDrawings);
// Edited: find xdr:to, or xdr:ext if xdr:to not exists
XmlNode befor = node.SelectSingleNode("xdr:to", NameSpaceManager);
if (befor != null && befor.Name == "xdr:to")
node.InsertAfter(picNode, befor);
else {
befor = node.SelectSingleNode("xdr:ext", NameSpaceManager);
node.InsertAfter(picNode, befor);
}
// End of change, next part of constructor is unchanged
_hyperlink = hyperlink;
...
Now, pictures are created as oneCellAnchor. If you want, you can create multiple AddPicture methods for booth variants. Last step is build this project and create your own custom EPPlus.dll. Then close your project which use this dll and copy new files EPPlus.dll, EPPlus.pdb, EPPlus.XML inside your project (backup and replace your original dll files) at the same place (so you don't need do any change in your project references or settings).
Then open and rebuild your project and try if this solve your problem.
Maybe I am too late, but here is mine answer..
you can read it on codeplex issue as well
(https://epplus.codeplex.com/workitem/14846)
I got this problem as well.
And after some research I figured out where the bug is.
It's in the ExcelRow class on the 149 line of code (ExcelRow.cs file).
There is a mistake, when row's Height got changed it recalcs all pictures heights but uses pictures widths inplace of heights, so it's easy to fix.
Just change the line
var pos = _worksheet.Drawings.GetDrawingWidths();
to
var pos = _worksheet.Drawings.GetDrawingHeight();
See the code changes on image
P.S. Actual for version 4.0.4

Select random record from combobox

How to select random item from a combo box, without selecting what is there already in the combobox.
I guess you want something like this:
Random random = new Random();
int newIndex = -1;
do {
newIndex = random.Next(comboBox.Items.Count);
} while (newIndex == comobBox.SelectedIndex && comboBox.Items.Count > 1);
comobBox.SelectedIndex = random.Next(comboBox.Items.Count);
Basically Combo box has items in string so if you can describe me some clear then we may help more anyway here is sample code
n you can do it
ComboBox b = new ComboBox();
Random rt = new Random();
string myText = "";
myText = b.Items[rt.Next(0, b.Items.Count - 1)].ToString();
You should use the Random class to get a random number between 0 and the max amount of items in the combobox. You should get this number repeatedly until you get one that doesn't match what is already selected within the combobox, like so:
Random random = new Random();
int newSelectedIndex = comboBox.SelectedIndex;
while (newSelectedIndex == comboBox.SelectedIndex) {
newSelectedIndex = random.Next(0, comboBox.Items.Count);
}
comboBox.SelectedIndex = newSelectedIndex;
// Item
// comboBox.Items[newSelectedIndex];
This may not work C/P'd, as I wrote it from the top of my head and don't have an IDE to test right now, but I hope you get the idea.
IMPORTANT: If you only have 1 item which is also selected, this may get into an endless loop...

Resources