ListView SelectedIndexChanged items getting inserted twice - c#

I have a list of clauses in my database and a listview in my custom pane in VSTO.
When I select or drag and drop a list item, it gets copied twice. I found this answer.
Listview ItemSelectionChanged fires twice?
But I dont have a isSelected method for my EventArgs e.
Below is my code, please help me out, I want the data/text to be copied only once.
private void clauseList_SelectedIndexChanged(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection col = clauseList.SelectedItems;
string temp = clauseList.FocusedItem.Text;
clauseList.DoDragDrop(temp, DragDropEffects.Move);
Microsoft.Office.Interop.Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
Microsoft.Office.Interop.Word.Range range = currentSelection.Range;
currentSelection.TypeText(temp);
currentSelection.TypeParagraph();
clslst(select);
}
public void clslst(object s)
{
DataAccess data = new DataAccess();
List<ClauseDetails> details = new List<ClauseDetails>();
details.AddRange(data.ClausesRelated(s));
string FromtextFromDoc;
FromtextFromDoc = Globals.ThisAddIn.Application.Selection.Text;
Microsoft.Office.Interop.Word.Document docs = Globals.ThisAddIn.Application.ActiveDocument;
List<string> clslist = new List<string>();
string aa = "";
int f = 0;
string tempindex = "";
foreach (Paragraph paragraph in docs.Paragraphs)
{
Style style = paragraph.get_Style() as Style;
string styleName = style.NameLocal;
//var sty = style.Font;
//fontstyle = sty.Name;
//fontsize = sty.Size;
if (styleName.Equals("Heading 1"))
{
f += 1;
if (f == 2)
{
tempindex = aa;
f = 0;
clslist.Add(tempindex);
aa = "";
}
}
if (f > 0)
{
aa += paragraph.Range.Text;
}
}
clslist.Add(aa);
List<string> ClausesNotPresent = new List<string>();
List<string> ClausesPresent = new List<string>();
for (int i = 0; i < clslist.Count; i++)
{
for (int j = 0; j < details.Count; j++)
{
if (clslist[i].Contains(details[j].clausetitle) || clslist[i].Contains(details[j].clause))
{
ClausesPresent.Add(details[j].clausetitle + "\n" + details[j].clause);
}
}
}
List<string> test = new List<string>();
for (int z = 0; z < details.Count; z++)
{
test.Add(details[z].clausetitle + "\n" + details[z].clause);
}
if (ClausesPresent.Count < details.Count)
{
ClausesNotPresent.AddRange(test.Except(ClausesPresent));
}
for(int m=0;m<ClausesNotPresent.Count;m++)
{
ClausesNotPresent[m] = "\n"+ ClausesNotPresent[m];
}
clauseList.Clear();
for (int i = 0; i < ClausesNotPresent.Count; i++)
{
clauseList.Items.Add(ClausesNotPresent[i]);
}
}

Related

Merge rows in datagridview

I am trying to make a billing software and want to merge the rows with same barcode with a press of a button, and if that row contains remark then the row should not merge.
private void button3_Click(object sender, EventArgs e)
{
int GROW = dataGridView1.RowCount;
for(int i=0; i<GROW; i++)
{
DataGridViewRow row= dataGridView1.Rows[i];
string A = row.Cells[0].Value.ToString();
for(int j = 0; j< GROW; j++)
{
if(j == i)
{
}
else
{
DataGridViewRow rowb= dataGridView1.Rows[j];
string B = rowb.Cells[0].Value.ToString();
if (A == B)
{
string rema = row.Cells[8].Value.ToString();
string remb = rowb.Cells[8].Value.ToString();
if(rema == "" && remb == "")
{
string qa = row.Cells[2].Value.ToString();
string qb = rowb.Cells[2].Value.ToString();
decimal qad = Convert.ToDecimal(qa);
decimal qbd = Convert.ToDecimal(qb);
decimal tqd = qad + qbd;
string ra = row.Cells[7].Value.ToString();
string rb = rowb.Cells[7].Value.ToString();
decimal rad = Convert.ToDecimal(ra);
decimal rbd = Convert.ToDecimal(rb);
decimal trd = rad + rbd;
row.Cells[7].Value = trd;
row.Cells[2].Value= tqd;
dataGridView1.Rows.RemoveAt(j);
// i = i - 1;
GROW--;
}
}
}
}
}
Assuming your value is in Cell[2] and remark in Cell[8], something like this should work:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
int k = 0;
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
// Check if values are same but remarks are different
if (dataGridView1.Rows[i].Cells[2].Value == dataGridView1.Rows[j].Cells[2].Value && dataGridView1.Rows[i].Cells[8].Value != dataGridView1.Rows[j].Cells[8].Value)
{
if (k != 0)
{
items.Rows.RemoveAt(j);
dataGridView1.DataSource = items;
}
k++;
}
}
}
NOTE: I have not tested this code but I hope you get the idea

Having result even by non exist inputs

I have a text file data set with following format (the separation character is tab).
0 762354
1 645645
2 4356743
3 576899063
4 64378
.....
that I read it and save it in array by:
for (int klk = 0; klk <= 92159; klk++)
{
lineuserori = fileuserori.ReadLine();
if (!string.IsNullOrEmpty(lineuserori))
{
string[] valuesiesi = lineitemori.Split('\t');
int useridori;
foreach (string value in valuesiesi)
{
useridori = Convert.ToInt32(valuesiesi[1]);
d[klk] = useridori;
}
}
}
NOW, I want to read an input and search for it in array d, if the number exist in array, I do my calculation, if it is not in array show MessageBox.Show("Error");, the problem is, it always show output with every input (even the input does not exist in array) and never show MessageBox.Show("Error");
{
int sc = Convert.ToInt32(txtbx_id.Text);
int n = Convert.ToInt32(txtbx_noofrecomm.Text);
for (int yu = 0; yu <= 92161; yu++)
{
int wer = d[yu];
if (wer == sc)
{
userseq = yu;
break;
}
}
if (userseq >= 0 && userseq <= 92161)
{
var results = new List<float>(1143600);
for (int z = 0; z < 1143600; z++)
{
results.Add(dotproduct(userseq, z));
}
var sb1 = new StringBuilder();
foreach (var resultwithindex in results.Select((r, index) => new { result = r, Index = index }).OrderByDescending(r => r.result).Take(n))
{
sb1.AppendFormat(CultureInfo.InvariantCulture, "{0}: {1}", c[resultwithindex.Index], resultwithindex.result);
sb1.AppendLine();
}
MessageBox.Show(sb1.ToString());
}
if (userseq < 0 || userseq > 92161)
{
MessageBox.Show("Error");
}
}
Any idea
Thanks
In your code to create array , is lineitemori right?
I think, it should be lineuserori.
Replace this:
string[] valuesiesi = lineitemori.Split('\t');
with:
string[] valuesiesi = lineuserori.Split('\t');
I wrote code below. (some lines uses unknown variables commented out)
Input 762354 to txtbx_id and click button1 then empty MessageBox appeared.
Input 76235 to txtbx_id and click button1 then MessageBox say 'Error'.
public partial class Form1 : Form {
// form have three controls txtbx_id, txtbx_noofrecomm and button1.
int[] d = new int[92162];
string data =
"0\t762354\n"
+"1\t645645\n"
+"2\t4356743\n"
+"3\t576899063\n"
+"4\t64378\n";
public Form1() {
InitializeComponent();
using (var fileuserori = new StringReader(data)) { // use StringReader instead of StreamReader
string lineuserori = "";
for (int klk = 0; klk <= 92159; klk++) {
lineuserori = fileuserori.ReadLine();
if (!string.IsNullOrEmpty(lineuserori)) {
// string[] valuesiesi = lineitemori.Split('\t');
string[] valuesiesi = lineuserori.Split('\t');
int useridori;
foreach (string value in valuesiesi) {
useridori = Convert.ToInt32(valuesiesi[1]);
d[klk] = useridori;
}
}
}
}
}
private void button1_Click(object sender, EventArgs e) {
var userseq = -1;
int sc = Convert.ToInt32(txtbx_id.Text);
int n = Convert.ToInt32(txtbx_noofrecomm.Text);
for (int yu = 0; yu <= 92161; yu++) {
int wer = d[yu];
if (wer == sc) {
userseq = yu;
break;
}
}
if (userseq >= 0 && userseq <= 92161) {
var results = new List<float>(1143600);
for (int z = 0; z < 1143600; z++) {
// results.Add(dotproduct(userseq, z));
}
var sb1 = new StringBuilder();
foreach (var resultwithindex in results.Select((r, index) => new { result = r, Index = index }).OrderByDescending(r => r.result).Take(n)) {
// sb1.AppendFormat(CultureInfo.InvariantCulture, "{0}: {1}", c[resultwithindex.Index], resultwithindex.result);
// sb1.AppendLine();
}
MessageBox.Show(sb1.ToString());
}
if (userseq < 0 || userseq > 92161) {
MessageBox.Show("Error");
}
}
}

Why won't the label populate

I have been trying to create a chess strategy application. I seem to be having issues with trying to get the label1 control to populate during run time. I am actually pretty new to the idea of dynamically creating events like 'mouse enter, mouse leave' How do I get the label to show the coordinates in the mouse enter event
int currentXposition, currentYposition;
const string positionLabel = "Current Position: ";
private void Test_Load(object sender, EventArgs a)
{
var temp=Color.Transparent; //Used to store the old color name of the panels before mouse events
var colorName = Color.Red; //Color used to highlight panel when mouse over
int numBlocks = 8; //Used to hold the number of blocks per row
int blockSize=70;
//Initialize new array of Panels new
string[,] Position = new string[8, 8];
Panel[,] chessBoardPanels = new Panel[numBlocks, numBlocks];
string Alphabet = "A,B,C,D,E,F,G,H";
string Numbers ="1,2,3,4,5,6,7,8";
string[] alphaStrings = Numbers.Split(',');
string[] numStrings=Numbers.Split(',');
// b = sub[0];
int FirstValue, SecondValue;
//Store Position Values
for (int firstValue = 0; firstValue < 8; ++firstValue)
{
FirstValue = Alphabet[firstValue];
for (int SecValue = 0; SecValue < 8; ++SecValue)
{
SecondValue = Numbers[SecValue];
Position[firstValue, SecValue] = alphaStrings[firstValue] + numStrings[SecValue];
}
}
//Loop to create panels
for (int iRow = 0; iRow < numBlocks; iRow++)
for (int iColumn = 0; iColumn < numBlocks; iColumn++)
{
Panel p = new Panel();
//set size
p.Size = new Size(blockSize, blockSize);
//set back colour
p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
//set location
p.Location = new Point(blockSize *iRow+15, blockSize * iColumn+15);
chessBoardPanels[iRow, iColumn] = p;
chessBoardPanels[iRow,iColumn].MouseEnter += (s,e) =>
{
currentXposition = iRow;
currentYposition = iColumn;
var oldColor = (s as Panel).BackColor;
(s as Panel).BackColor = colorName;
temp = oldColor;
label1.Text = Position[iRow, iColumn];
};
chessBoardPanels[iRow, iColumn].MouseLeave += (s, e) =>
{
(s as Panel).BackColor = temp;
};
groupBox1.Controls.Add(p);
}
}
Try this.. It was not populating because of a out of range.. iRow always = 8...
Add this class to your project.
public class ChessSquare
{
public string Letter { get; set; }
public int Number { get; set; }
public Color Color { get; set; }
public string Position
{
get { return string.Format("{0}{1}", Letter, Number); }
}
public ChessSquare()
{
}
public ChessSquare(string letter, int number)
{
Letter = letter;
Number = number;
}
}
Replace the FormLoad method with this:
int blockSize = 20;
Panel[,] chessBoardPanels = new Panel[8, 8];
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
ChessSquare sq = new ChessSquare(((char)(65+i)).ToString(), j);
sq.Color = (i + (j % 2)) % 2 == 0 ? Color.AliceBlue : Color.White;
Panel p = new Panel()
{ Size = new Size(blockSize, blockSize),
BackColor = sq.Color,
Tag = sq,
Location = new Point(blockSize * i + 15, blockSize * j+15),
};
p.MouseEnter+=new EventHandler(squareMouseEnter);
p.MouseLeave += new EventHandler(squareMouseLeave);
chessBoardPanels[i, j] = p;
groupBox1.Controls.Add(p);
}
}
And add those two methods to your code:
void squareMouseEnter(object sender, EventArgs e)
{
Panel p = (Panel)sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = Color.Aqua;
label1.Text = string.Format("Current position: {0}", sq.Position);
}
void squareMouseLeave(object sender, EventArgs e)
{
Panel p = (Panel) sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = sq.Color;
}
I there are several ways of doing it... This one is pretty straight forward.

How to get the values dynamically added controls in other parts of the code?

I have a method that creates textboxes depending on the number of parameters values that the user has to enter.And its working fine. The problem is that when the user clicks Ok i want to take the value that the user entered in these textboxes and replace them in a string. When am searching these textboxes to get the text value from them am not finding them. How do i get these values to continue my project? the code is:
protected void btnPreview_Click(object sender, EventArgs e)
{
lbHeader.Text = "Template Designer";
divQueryBuilder.Visible = false;
divTemplateDesigner.Visible = false;
divFloating.Visible = true;
if (txtQuery.Text.Contains("WHERE") || txtQuery.Text.Contains("where")||txtQuery.Text.Contains("Where"))
{
string[] splitter=new string[10];
splitter[0]="Where";
splitter[1]="WHERE";
splitter[2]="where";
splitter[3]="AND";
splitter[4] = "and";
splitter[5] = "And";
string[] condition=txtQuery.Text.Split(splitter, StringSplitOptions.None);
int numberOfParameters = condition.Length - 1;
string[] Condition1 =null;
Label[] newLabel = new Label[10];
TextBox[] txtBox = new TextBox[10];
for (int i = 0; i < numberOfParameters; i++)
{
string lbValue="lbValue";
string lbID=lbValue+i;
string txtValue = "txtValue";
string txtID = txtValue + i;
HtmlGenericControl genericControl = new HtmlGenericControl("br/");
Condition1 = condition[i + 1].Split('[', ']');
newLabel[i] = new Label();
txtBox[i] = new TextBox();
newLabel[i].ID=lbID;
newLabel[i].Text = Condition1[1];
txtBox[i].ID = txtID;
td2.Controls.Add(newLabel[i]);
td2.Controls.Add(genericControl);
td2.Controls.Add(txtBox[i]);
td2.Controls.Add(genericControl);
txtBox[i].EnableViewState = true;
}
}
}
private bool ControlExistence(string lbID)
{
try
{
td2.FindControl(lbID);
return true;
}
catch(Exception ex)
{
return false;
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
// GetTextBoxValues();
string[] splitter1 = new string[10];
splitter1[0] = "Where";
splitter1[1] = "WHERE";
splitter1[2] = "where";
splitter1[3] = "AND";
splitter1[4] = "and";
splitter1[5] = "And";
string[] condition = txtQuery.Text.Split(splitter1, StringSplitOptions.None);
int numberOfParameters = condition.Length - 1;
string[] splitter = new string[4];
splitter[0] = "[";
splitter[1] = "]";
splitter[2] = "'";
string[] queryBoxValue = txtQuery.Text.Split(splitter,StringSplitOptions.RemoveEmptyEntries);
StringBuilder query = new StringBuilder();
TextBox txtBox = new TextBox();
for (int i = 0; i < queryBoxValue.Length; i++)
{
if (!queryBoxValue[i].Contains("?"))
{
query.Append(queryBoxValue[i]);
query.Append(" ");
}
else
{
for (int counter1 = 0; counter1 < numberOfParameters; counter1++)
{
string txtValue = "txtValue";
string txtID = txtValue + counter1;
if (ControlExistence(txtID))
{
TextBox box = (TextBox)td2.FindControl(txtID);
string b = box.Text;
//txtBox.ID = txtID;
}
txtBox.Text = "'" + txtBox.Text + "'";
queryBoxValue[i] = queryBoxValue[i].Replace(queryBoxValue[i], txtBox.Text);
query.Append(queryBoxValue[i]);
}
}
}
string fireQuery = query.ToString();
adp = new SqlDataAdapter(fireQuery, conn);
tab = new DataTable();
adp.Fill(tab);
if (tab.Rows.Count > 0)
{
string[] tempString = txtTemplate.Text.Split(' ');
for (int j = 0; j < tempString.Length; j++)
{
if (tempString[j].StartsWith("["))
{
txtPreview.Text = txtTemplate.Text.Replace(tempString[j], tab.Rows[0][0].ToString());
}
}
}
divFloating.Visible = false;
divQueryBuilder.Visible = false;
divTemplateDesigner.Visible = true;
}
Please help. This has become a blocker for me.
Have a list of the added controls and use it when needed.
for (int i = 0; i < numberOfParameters; i++)
{
// ...
td2.Controls.Add(newLabel[i]);
td2.Controls.Add(genericControl);
td2.Controls.Add(txtBox[i]);
td2.Controls.Add(genericControl);
addedTextBoxes.Add(txtBox[i]);
// ...
}
And then from another part of your code:
var values = addedTextBoxes.Select(tb => tb.Text).ToList();
foreach (var txtBox in addedTextBoxes)
{
// ...
}
etc...

files in folder in listview

I want to make a listview of files in folder,but it doesn't work. What's wrong with this code?
DialogResult wczytywanie_z_folderu = new DialogResult();
wczytywanie_z_folderu = folderBrowserDialog1.ShowDialog();
string[] pliki_w_folderze = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
if (wczytywanie_z_folderu == DialogResult.OK)
{
List<string> lista = new List<string>();
lista = pliki_w_folderze.ToList();
int dl_listy = lista.Count;
int dlugosc = pliki_w_folderze.Length;
for (int i = 0; i == dlugosc; i = i + 1)
{
string alfabet = "abcdefghijklmnopqrstuwvxyz";
char[] litery = alfabet.ToCharArray();
Random r = new Random();
string temp = "";
for (int j = 0; j < 1; j++)
{
int random_letter = r.Next(litery.Length);
temp += litery[random_letter].ToString();
ListViewItem str = new ListViewItem(temp);
str.Text = lista[i];
listView1.Items.Add(str);
}
}
Your for should be:
for (int i = 0; i < dlugosc; i = i + 1)
Better yet, use foreach!
It's not clear why you're going through all the random numbers to get an alphabet char, only to simply overwrite the Text property with the name of the file.
Try this instead, to help make life easier.
if (wczytywanie_z_folderu == DialogResult.OK)
{
listview1.Items.AddRange( pliki_w_folderze
.Select(f => new ListViewItem(f))
.ToArray());
}

Categories