I have a tabcontrol in my application. I have a listbox which contains the line no of error and file name and path of the file.On double click i want to add the new tab page.The title of the tabpage should be the name of file from the listbox. If the tabpage with the particular filename already exists then it should not open new tabpage the cursor should point to that page. How to retreive the name of the tabpages .
private void lstErrorList_MouseDoubleClick(object sender, MouseEventArgs e)
{
ArrayList errorType = new ArrayList();
if (lstErrorList.Items.Count > 0)
{
string error = lstErrorList.SelectedItem.ToString();
{
int result = error.LastIndexOf('\\');
string filename = error.Substring(result + 1, error.Length - (result + 1));
int pagecount;
TabPage tp = new TabPage();
pagecount = this.tabControl1.TabPages.Count;
for(int tbpagecount=0;tbpagecount<pagecount;tbpagecount++)
{
pagelist.Add(this.tabControl1.TabPages.ToString());
}
if (pagelist.Contains(filename))
{
}
else
{
this.tabControl1.TabPages.Insert(pagecount, filename);
pagecount++;
}
if (fileNamesList.Count == 0)
fileNamesList.Add(filename);
else
{
if (fileNamesList.Contains(filename))
{
//fileNamesList.Add("");
}
else
{
fileNamesList.Add(filename);
}
}
}
bool found = false;
foreach (TabPage tab in tabControl1.TabPages) {
if (filename.Equals(tab.Name)) {
tabControl1.SelectedTab = tab;
found = true;
}
}
if( ! found)
tabControl1.TabPages.Add(filename,filename);
var tabPage = tabControl1.TabPages[filename];
if (tabPage != null)
{
tabControl1.SelectedTab = tabPage;
}
else
{
tabControl1.TabPages.Add(filename, filename);
}
What about something like this?
string fileName = "";
bool isPresent = false;
for (int i = 0; i < tabControl1.TabPages.Count; i++)
{
if (tabControl1.TabPages[i].Name == filename)
{
isPresent = true;
break;
}
}
if (isPresent)
{
tabControl1.TabPages.Add(filename);
}
else
{
tabControl1.SelectTab(tab.TabIndex);
}
Related
I built a winform project. This project open a mhtml file, then, he display the datagrid and remove the empty column.
i used much time "invoke" in my code. I would like to know how can i put this data into a DataTable or List and then binded the grid to it.
Here is the code :
{
public partial class Form1 : Form
{
private readonly string ConvertedFileName = "page.html";
private readonly List<string> ColumnsToSeparate = new List<string>() { "life limit", "interval" }; // Delete these columns
private readonly List<string> ExtraColumnsToAdd = new List<string>() { "Calendar", "Flight Hours", "Landing" }; // Add these columns
public Form1()
{
InitializeComponent();
this.Text = $"MhtmlTablesHunter v{Application.ProductVersion}";
}
//browse for specific file type , in this case its .mhtml
private void btnBrowse_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Title = "Please choose the MHTML file";
openFileDialog.Filter = "MHTML files (*.mhtml)|*.mhtml;"; //the file type specified here
openFileDialog.RestoreDirectory = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
textBoxSourceFile.Text = openFileDialog.FileName;
checkAndExtractTable();
}
}
}
private void checkAndExtractTable()
{
string sourcePath = textBoxSourceFile.Text;
if (!string.IsNullOrEmpty(sourcePath)) //check if the input file path is not empty
{
if (File.Exists(sourcePath)) //check if the input file path is exists
{
Task.Run(async () => await ExtractTable(sourcePath)); //run the extraction process in a thread for the UI to be more responsive
}
else
{
MessageBox.Show("Source file doesn't exist.");
}
}
else
{
MessageBox.Show("Please select the source file.");
}
}
//This part concern the headers, rows and columns
public async Task<string> ExtractTable(string sourcePath)
{
try
{
var doc = new HtmlAgilityPack.HtmlDocument();
var converter = new MimeConverter(); //converter used to convert mhtml file to html
if (File.Exists(ConvertedFileName)) //check if previously converted file is exist
{
File.Delete(ConvertedFileName); //delete the file
}
using (FileStream sourceStream = File.OpenRead(sourcePath))
{
using (FileStream destinationStream = File.Open("page.html", FileMode.Create))
{
await converter.Convert(sourceStream, destinationStream); //convert the file to html, it will be stored in the application folder
}
}
doc.Load(ConvertedFileName); //load the html
var tables = doc.DocumentNode.SelectNodes("//table"); //get all the tables
HtmlAgilityPack.HtmlNode table = null;
if (tables.Count > 0)
{
table = tables[tables.Count - 1]; //take the last table
}
if (table != null) //if the table exists
{
dataGridView1.Invoke((Action)delegate //we use delegate because we accessing the datagridview from a different thread
{
this.dataGridView1.Rows.Clear();
this.dataGridView1.Columns.Clear();
});
var rows = table.SelectNodes(".//tr"); //get all the rows
var nodes = rows[0].SelectNodes("th|td"); //get the header row values, first item will be the header row always
string LifeLimitColumnName = ColumnsToSeparate.Where(c => nodes.Any(n => n.InnerText.ToLower().Contains(c))).FirstOrDefault();
if (string.IsNullOrWhiteSpace(LifeLimitColumnName))
{
LifeLimitColumnName = "Someunknowncolumn";
}
List<string> headers = new List<string>();
for (int i = 0; i < nodes.Count; i++) // LOOP
{
headers.Add(nodes[i].InnerText);
if (!nodes[i].InnerText.ToLower().Contains(LifeLimitColumnName))
{
dataGridView1.Invoke((Action)delegate
{
dataGridView1.Columns.Add("", nodes[i].InnerText);
});
}
}
int indexOfLifeLimitColumn = headers.FindIndex(h => h.ToLower().Contains(LifeLimitColumnName));
if (indexOfLifeLimitColumn > -1)
{
foreach (var eh in ExtraColumnsToAdd)
{
dataGridView1.Invoke((Action)delegate
{
dataGridView1.Columns.Add("", eh); //add extra header to the datagridview
});
}
}
for (int i = 1; i < rows.Count; i++) ///loop through rest of the rows
{
var row = rows[i];
var nodes2 = row.SelectNodes("th|td"); //get all columns in the current row
List<string> values = new List<string>(); //list to store row values
for (int x = 0; x < nodes2.Count; x++)
{
//rowes.Cells[x].Value = nodes2[x].InnerText;
string cellText = nodes2[x].InnerText.Replace(" ", " ");
values.Add(cellText); //add the cell value in the list
}
// Factory for -> Calendar, Flight Hours, Landings
if (indexOfLifeLimitColumn > -1)
{
values.RemoveAt(indexOfLifeLimitColumn);
string lifeLimitValue = nodes2[indexOfLifeLimitColumn].InnerText.Replace(" ", " ");
string[] splittedValues = lifeLimitValue.Split(' ');
for (int y = 0; y < ExtraColumnsToAdd.Count; y++)
{
if (ExtraColumnsToAdd[y] == "Calendar")
{
string valueToAdd = string.Empty;
string[] times = new string[] { "Years", "Year", "Months", "Month", "Day", "Days" };
if (splittedValues.Any(s => times.Any(t => t == s)))
{
var timeFound = times.Where(t => splittedValues.Any(s => s == t)).FirstOrDefault();
int index = splittedValues.ToList().FindIndex(s => s.Equals(timeFound));
valueToAdd = $"{splittedValues[index - 1]} {timeFound}";
}
values.Add(valueToAdd);
}
else if (ExtraColumnsToAdd[y] == "Flight Hours")
{
string valueToAdd = string.Empty;
if (splittedValues.Any(s => s == "FH"))
{
int index = splittedValues.ToList().FindIndex(s => s.Equals("FH"));
valueToAdd = $"{splittedValues[index - 1]} FH";
}
values.Add(valueToAdd);
}
else
{
string valueToAdd = string.Empty;
if (splittedValues.Any(s => s == "LDG"))
{
int index = splittedValues.ToList().FindIndex(s => s.Equals("LDG"));
valueToAdd = $"{splittedValues[index - 1]} LDG";
}
values.Add(valueToAdd);
}
}
}
dataGridView1.Invoke((Action)delegate
{
this.dataGridView1.Rows.Add(values.ToArray()); //add the list as a row
});
}
//This code remove the empty row
dataGridView1.Invoke((Action)delegate
{
int[] rowDataCount = new int[dataGridView1.Columns.Count];
Array.Clear(rowDataCount, 0, rowDataCount.Length);
for (int row_i = 0; row_i < this.dataGridView1.RowCount; row_i++)
{
for (int col_i = 0; col_i < this.dataGridView1.ColumnCount; col_i++)
{
var cell = this.dataGridView1.Rows[row_i].Cells[col_i];
string cellText = cell.Value.ToString();
if (!String.IsNullOrWhiteSpace(cellText))
{
rowDataCount[col_i] += 1;
}
}
}
int removedCount = 0;
for (int index = 0; index < rowDataCount.Length; index++)
{
if (rowDataCount[index] == 0)
{
this.dataGridView1.Columns.RemoveAt(index - removedCount);
removedCount++;
}
}
});
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return string.Empty;
}
private void textBoxSourceFile_TextChanged(object sender, EventArgs e)
{
}
}
}
Somebody can help me please? thanks a lot !
How do I change the autocomplete on a TextBox? I want that when I type a string, the box suggest items containing that string instead of starting with.
My code is:
class MyClass
{
private AutoCompleteStringCollection autoCompleteList = new AutoCompleteStringCollection();
public MyClass()
{
InitializeComponent();
autoCompleteList.AddRange(ListNames.Select(x=>x.Name).ToArray());
textBoxName.AutoCompleteCustomSource = autoCompleteList;
textBoxName.AutoCompleteSource = AutoCompleteSource.CustomSource;
textBoxName.AutoCompleteMode = AutoCompleteMode.Suggest;
textBoxName.KeyDown += TextBoxtextName_KeyDown;
}
private void TextBoxClient_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
this.Name = (sender as TextBox).Text;
}
}
}
What I want:
Looking at your code you have everything you need but 1 line of code. That line is:
This will only work if the start of a string is entered
//Suggestion only
textBoxName.AutoCompleteMode = AutoCompleteMode.Suggest;
//Suggest and autocomplete
textBoxName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
This will work as a contains method but works with a custom control
You can also make a custom textbox control that fits your needs.
Custom textbox class:
public class AutoCompleteTextBox : TextBox
{
private ListBox _listBox;
private bool _isAdded;
private String[] _values;
private String _formerValue = String.Empty;
public AutoCompleteTextBox()
{
InitializeComponent();
ResetListBox();
}
private void InitializeComponent()
{
_listBox = new ListBox();
this.KeyDown += this_KeyDown;
this.KeyUp += this_KeyUp;
}
private void ShowListBox()
{
if (!_isAdded)
{
Parent.Controls.Add(_listBox);
_listBox.Left = Left;
_listBox.Top = Top + Height;
_isAdded = true;
}
_listBox.Visible = true;
_listBox.BringToFront();
}
private void ResetListBox()
{
_listBox.Visible = false;
}
private void this_KeyUp(object sender, KeyEventArgs e)
{
UpdateListBox();
}
private void this_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
case Keys.Tab:
{
if (_listBox.Visible)
{
Text = _listBox.SelectedItem.ToString();
ResetListBox();
_formerValue = Text;
this.Select(this.Text.Length, 0);
e.Handled = true;
}
break;
}
case Keys.Down:
{
if ((_listBox.Visible) && (_listBox.SelectedIndex < _listBox.Items.Count - 1))
_listBox.SelectedIndex++;
e.Handled = true;
break;
}
case Keys.Up:
{
if ((_listBox.Visible) && (_listBox.SelectedIndex > 0))
_listBox.SelectedIndex--;
e.Handled = true;
break;
}
}
}
protected override bool IsInputKey(Keys keyData)
{
switch (keyData)
{
case Keys.Tab:
if (_listBox.Visible)
return true;
else
return false;
default:
return base.IsInputKey(keyData);
}
}
private void UpdateListBox()
{
if (Text == _formerValue)
return;
_formerValue = this.Text;
string word = this.Text;
if (_values != null && word.Length > 0)
{
string[] matches = Array.FindAll(_values,
x => (x.ToLower().Contains(word.ToLower())));
if (matches.Length > 0)
{
ShowListBox();
_listBox.BeginUpdate();
_listBox.Items.Clear();
Array.ForEach(matches, x => _listBox.Items.Add(x));
_listBox.SelectedIndex = 0;
_listBox.Height = 0;
_listBox.Width = 0;
Focus();
using (Graphics graphics = _listBox.CreateGraphics())
{
for (int i = 0; i < _listBox.Items.Count; i++)
{
if (i < 20)
_listBox.Height += _listBox.GetItemHeight(i);
// it item width is larger than the current one
// set it to the new max item width
// GetItemRectangle does not work for me
// we add a little extra space by using '_'
int itemWidth = (int)graphics.MeasureString(((string)_listBox.Items[i]) + "_", _listBox.Font).Width;
_listBox.Width = (_listBox.Width < itemWidth) ? itemWidth : this.Width; ;
}
}
_listBox.EndUpdate();
}
else
{
ResetListBox();
}
}
else
{
ResetListBox();
}
}
public String[] Values
{
get
{
return _values;
}
set
{
_values = value;
}
}
public List<String> SelectedValues
{
get
{
String[] result = Text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
return new List<String>(result);
}
}
}
Usage:
string[] nameArray = { "name1", "name2", "name3", "bla name" };
AutoCompleteTextBox tb = new AutoCompleteTextBox();
tb.Values = nameArray;
tb.Location = new Point(10,10);
tb.Size = new Size(25,75);
this.Controls.Add( tb );
I got the code for the custom control from: SO Question - Autocomplete contains
When I select a particular item in ListView item, I am able to display that particular item, and when the form loads I am getting the last item displayed by default (say the 10th item). However, what I want is to display the first item by default. How can I do this? I tried to do something like
listView1.Items[1].Selected = true;
but it's not working:
public partial class GroupExmStart : Form
{
string[] totDisplayQsn = null;
string[] QAndA = null;
string[] words = null;
private List<Question> questions;
ListViewItem lvi;
public GroupExmStart(string GroupName, string DurationID)
{
InitializeComponent();
this.GrpID=GroupName;
TopiID=db.GetTopicIDForGroup(GrpID);
string[] conf = db.GetConfiguration(Convert.ToInt16(DurationID)).Split('|');
Question qsn = new Question();
questions = qsn.Foo(TopiID, conf);
int z = Quiz(questions);
totQsn = Convert.ToInt16(conf[0]);
for (int kk = 1; kk <= totQsn; kk++)//using this I am adding items to listview
{
lvi = new ListViewItem();
lvi.Text = kk.ToString();
listView1.Items.Add(lvi);
}
totDisplayQsn = new string[totQsn + 1];
}
int Quiz(List<Question> questions)//using this I a passing set of questions to be displayed
{
foreach (Question question in questions)
{
DisplayQuestion(question);
}
return 0;
}
private void DisplayQuestion(Question question)//using this i am displaying questions
{
string Q = question.Text;
label5.Text = Q;
string OP1 = question.Option1;
string OP2 = question.Option2;
string OP3 = question.Option3;
string OP4 = question.Option4;
radioButton12.Text = OP4;
radioButton11.Text = OP4;
radioButton10.Text = OP4;
radioButton9.Text = OP4;
}
}
private void listView1_MouseClick(object sender, MouseEventArgs e)//using this i am selection particular item and displaying it
{
if (totDisplayQsn.GetLength(0) >= 0)
{
if (listView1.SelectedItems.Count > 0)
{
var q = Convert.ToInt16(listView1.SelectedItems[0].Text);
var selectedQuestion = questions[q-1];
DisplayQuestion(selectedQuestion);
}
}
}
Thanks in advance for any help.
Try this
listView1.SelectedItems[0].Focused = true;
To select the first item, access it by its zero based index. Place the code just after your items initialization code.
for (int kk = 1; kk <= totQsn; kk++)//using this I am adding items to listview
{
lvi = new ListViewItem();
lvi.Selected = false;
lvi.Text = kk.ToString();
listView1.Items.Add(lvi);
}
listView1.Items[0].Selected = true;
DisplayQuestion(questions[0]);
Remove the following code:
int Quiz(List<Question> questions)//using this I a passing set of questions to be displayed
{
foreach (Question question in questions)
{
DisplayQuestion(question);
}
return 0;
}
Ok try the below code:
ListViewItem foundItem = listView1.FindItemWithText("Select4", false, 0, true);
if (foundItem != null)
{
listView1.Items[foundItem.Index].Selected = true;
}
That's All.
I have a listview which binds the customer infos. Also, I have a textbox which provides searching in the listview. If the textbox's typed character or symbol matches with a datalist item then it highlights the matched item. Concerning this, I want to count the matched items number. But every search the count is "0". When I debug it then the count is true in the foreach loop but it is always zero in the TxtSearch_PreviewKeyDown. Please have a look. How can I found out the matched item amount?
private int highlightcount;
public int highlightCount
{
get;
set;
}
private void FindListViewItem(DependencyObject obj)
{
try
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
ListViewItem lv = obj as ListViewItem;
if (lv != null)
{
HighlightText(lv);
}
else
FindListViewItem(VisualTreeHelper.GetChild(obj as DependencyObject, i));
}
}
catch
{
MessageBox.Show("Bevor Sie die Suche Stauten, wählen Sie bitte eine Adresse in der linken Spalte aus.");
}
}
/// <summary>
/// Method for highlighting matched listview item
/// </summary>
/// <param name="itx"></param>
public void HighlightText(Object itx)
{
try
{
if (itx != null)
{
if (itx is TextBlock)
{
Regex regex = new Regex("(" + TxtSearch.Text + ")", RegexOptions.IgnoreCase);
TextBlock tb = itx as TextBlock;
if (TxtSearch.Text.Length == 0)
{
string str = tb.Text;
tb.Inlines.Clear();
tb.Inlines.Add(str);
return;
}
string[] substrings = regex.Split(tb.Text);
tb.Inlines.Clear();
highlightCount = 0;
foreach (var item in substrings)
{
if (regex.Match(item).Success)
{
Run runx = new Run(item);
runx.Background = Brushes.Lime;
tb.Inlines.Add(runx);
highlightCount++;
if (tb.IsMouseOver)
{
tb.IsEnabled = false;
}
}
else
{
tb.Inlines.Add(item);
tb.IsEnabled = false;
}
}
return ;
}
else
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(itx as DependencyObject); i++)
{
HighlightText(VisualTreeHelper.GetChild(itx as DependencyObject, i));
}
}
}
}
catch
{
MessageBox.Show("Suche Error");
}
}
private void TxtSearch_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (TxtSearch.Text.Length > 1 && e.Key==Key.Enter)
{
Mouse.OverrideCursor = Cursors.Wait;
ListControl lc = getactivListview();
FindListViewItem(lc);
Mouse.OverrideCursor = null;
MessageBox.Show(highlightCount.ToString());
FocusManager.SetFocusedElement(this, TxtSearch);
}
Try removing highlightCount = 0; from your HighlightText method and add it to the TxtSearch_PreviewKeyDown Eventhandler (over ListControl lc = getactivListview(); or under MessageBox.Show(highlightCount.ToString());)
I will have a treenode with some nodes. I will have a datagridview on my form. Initially i will load some data in to the gridview. Now if i select a node at my trreview i would like to make a particular row as selected one.
Suppose my treeview is as follows
Root
|-> Child
|->Child1
If i select child i would like to make a corresponding row as selected if child1 another row should get selected.
Any idea please
1) you need to map the nodes to corresponding datagrid rows
this.dataGridView1.Rows[0].Tag = id; // a node id
2) handle node click event and find corresponding row by id and select it
if (tvwACH.SelectedNode.Parent != null)
{
int id = (int)tvwACH.SelectedNode.Tag ; // make sure you've already assigned tag when creating Three nodes and data rows
foreach(DataGridViewRow row in this.dataGridView1.Rows)
{
int rowId = (int)row.Tag ;
if(rowId == id)
{
row.Selected = ture;
}
else
{
row.Selected = false; //discard other rows
}
}
}
yourDataGridView.Rows(nRowIndex).Selected = true;
This is the code i have written
private void tvwACH_AfterSelect(object sender, TreeViewEventArgs e)
{
string node = string.Empty;
if (tvwACH.SelectedNode.Parent != null)
{
node = tvwACH.SelectedNode.Text.ToString();
if (node == "FileHeader")
{
int tag = Convert.ToInt16(tvwACH.SelectedNode.Tag.ToString());
this.dataGridView1.Rows[0].Tag = tag;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
int rowId = (int)row.Tag;
if (rowId == tag)
{
row.Selected = true;
}
}
}
string strSwitch = tvwACH.SelectedNode.Parent.Text;
switch (strSwitch)
{
case "ACH":
{
dataGridView1.Visible = true;
dataGridView1.Rows.Clear();
node = tvwACH.SelectedNode.Text;
StreamReader sr = new StreamReader(node);
while (sr.Peek() >= 0)
{
string line = sr.ReadLine();
dataGridView1.Rows.Add(rectype[line.Substring(0, 1)].ToString(), line);
}
sr.Close();
}
break;
}
}
}
Try this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int flage = 1;
private void button1_Click(object sender, EventArgs e)
{
flage = 1;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Selected)
{
DataGridViewRow currentRow = dataGridView1.SelectedRows[0];
TreeNode node1 = new TreeNode(currentRow.Cells[1].Value.ToString());
TreeNode node2 = new TreeNode(currentRow.Cells[2].Value.ToString());
TreeNode node3 = new TreeNode(currentRow.Cells[3].Value.ToString());
TreeNode[] TreeArray = new TreeNode[] { node1,node2, node3 };
TreeNode finalnode = new TreeNode(currentRow.Cells[0].Value.ToString(), TreeArray);
treeView1.Nodes.Add(finalnode);
flage = 1;
break;
}
else
{
flage = 0;
}
}
if(flage==0)
{
MessageBox.Show("Row is not Selected Please select the row");
}
}
private void button2_Click(object sender, EventArgs e)
{
treeView1.Nodes.Remove( treeView1.SelectedNode);
}
int flage2;
private void button3_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Selected)
{
dataGridView1.Rows.Remove(dataGridView1.SelectedRows[0]);
flage2 = 1;
break;
}
else
{
flage2 = 0;
}
}
if (flage2 == 0)
{
MessageBox.Show("Row is not selected Please select the row");
}
}
}