How to make a customized progressbar in c# - c#

I would like to learn how to make a progressbar like the one shown in this video.
I tried to replicate it in VS C#, but I get the error:
C# Property or indexer cannot be assigned to -- it is read only
If I try using if (txProgressBar.Text.Length == 85), I will get this in the TextBox (txProgressBar)
System.Windows.Forms.TextBox, Text: System.Windows.Forms.TextBox, Text: Syst...██
Textbox Progressbar Tutorial VB 2010
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CustomizedProgressBar
{
public partial class Form1 : Form
{
int last = 1;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (txProgressBar.Text.Length = "85")
{
timer1.Stop();
MessageBox.Show("Counted!");
}else
{
if (last == 1)
{
txProgressBar.Text = txProgressBar + "█";
last = 2;
}
else
{
txProgressBar.Text = txProgressBar.Text + "█";
last = 1;
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txProgressBar.Text = "";
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Stop();
}
}
}

Your line:
txProgressBar.Text = txProgressBar + "█";
should be
txProgressBar.Text = txProgressBar.Text + "█"; or txProgressBar.Text &= "█";

I realized what was the problem. The txProgressBar.Text = txProgressBar + "█"; was missing the *.Text. That solved the problem and the message is shown as well.

Related

How to display the route using GMap in C#?

My main problem is that it doesn't display the line between the 2 markers when I click on the display button.It should draw my route between the first pin and the second pin, but it doesn't show me anything at all. I've been trying for some time to figure out what's wrong.
This is the code. I also uploaded images, maybe it will help.
Can anyone help me with this? Thanks!
code
interface
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using GMap.NET.MapProviders;
using GMap.NET;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
namespace Licenta
{
public partial class Map : Form
{
List<PointLatLng> _points;
public Map()
{
InitializeComponent();
_points = new List<PointLatLng>();
}
private void Map_Load(object sender, EventArgs e)
{
GMapProviders.GoogleMap.ApiKey = "#AIzaSyBreQ8N4txQ74BwKwigtnmkSW8Vhisyles";
gMapControl1.ShowCenter = false;
}
private void btnAdauga_Click(object sender, EventArgs e)
{
_points.Add(new PointLatLng(Convert.ToDouble(txtLat.Text), Convert.ToDouble(txtLong.Text)));
}
private void btnSterge_Click(object sender, EventArgs e)
{
if (gMapControl1.Overlays.Count > 0)
{
gMapControl1.Overlays.RemoveAt(0);
gMapControl1.Refresh();
}
}
private void btnAfiseaza_Click(object sender, EventArgs e)
{
var route = GoogleMapProvider.Instance.GetRoute(_points[0], _points[1], false, false, 14);
var r = new GMapRoute(route.Points, "My Route")
{
Stroke = new Pen(Color.Red, 5)
};
var routes = new GMapOverlay("routes");
routes.Routes.Add(r);
gMapControl1.Overlays.Add(routes);
lblDist.Text = route.Distance + " km";
}
GMapOverlay markers = new GMapOverlay("markers");
private void btnIncarca_Click(object sender, EventArgs e)
{
gMapControl1.DragButton = MouseButtons.Left;
gMapControl1.MapProvider = GMapProviders.GoogleMap;
double lat = Convert.ToDouble(txtLat.Text);
double longt = Convert.ToDouble(txtLong.Text);
gMapControl1.Position = new PointLatLng(lat, longt);
gMapControl1.MinZoom = 2;
gMapControl1.MaxZoom = 100;
gMapControl1.Zoom = 7;
PointLatLng point = new PointLatLng(lat, longt);
GMapMarker marker = new GMarkerGoogle(point, GMarkerGoogleType.red_pushpin);
markers.Markers.Add(marker);
gMapControl1.Overlays.Add(markers);
}
private void gMapControl1_Load(object sender, EventArgs e)
{
gMapControl1.SetPositionByKeywords("Timisoara, Romania");
}
private void button5_Click(object sender, EventArgs e)
{
_points.Clear();
}
}
}

C#: serial com not showing the whole data

Dear experts i am trying to access the serial port programmatically through C#.I have interface a gsm module serially for communication.problem i am facing is if data is small m getting it perfectly but when i am reading the all messages{AT+CMGL="ALL"} i am receiving only half data on contrary in third party application i am receiving the whole data.
so want to know where the problem is coming whether i have to inc the size of input buffer where the Readexisting() function storing data or have to increase the timeout?.Last i checked we can not vary the size of buffer. please help.
my code is as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace SERIAL_PORT
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getavailableports();
}
void getavailableports()
{
string[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void Button1_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "")
{
MessageBox.Show("please select port");
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.Open();
progressBar1.Value = 100;
// textBox2.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
textBox1.Enabled = true;
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("no");
}
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
progressBar1.Value = 0;
button6.Enabled = false;
button7.Enabled = false;
textBox1.Enabled = false;
//textBox2.Enabled = false;
}
private void button6_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(textBox1.Text + "");
textBox1.Text = "";
}
private void button7_Click(object sender, EventArgs e)
{
richTextBox1.Text = serialPort1.ReadExisting();
}
}
}

I'm trying to use backgroundworker with webBrowser to download images but getting exception. What should i do?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using HtmlAgilityPack;
using mshtml;
using System.Text.RegularExpressions;
namespace Extract_Images
{
public partial class Form1 : Form
{
private string[] linkstoextract;
private int numberoflinks;
private int currentLinkNumber = 0;
private string mainlink;
private WebClient client;
private WebBrowser webBrowser1;
private string htmlCode;
private bool pagesorimages = false;
public Form1()
{
InitializeComponent();
webBrowser1 = new WebBrowser();
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
label1.Text = "Number of links: ";
mainlink = "http://www.test.com/";
numberoflinks = 13;
backgroundWorker1.RunWorkerAsync();
}
private void ProcessNextLink()
{
if (currentLinkNumber < numberoflinks)
{
currentLinkNumber++;
string linktonav = mainlink + "index"+currentLinkNumber.ToString() + ".html";
pagesorimages = false;
backgroundWorker1.ReportProgress(0,currentLinkNumber);
webBrowser1.Navigate(linktonav);
}
}
int count = 0;
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
mshtml.HTMLDocument objHtmlDoc = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
string pageSource = objHtmlDoc.documentElement.innerHTML;
List<string> links = new List<string>();
string[] hrefs = this.webBrowser1.Document.Links.Cast<HtmlElement>()
.Select(a => a.GetAttribute("href")).Where(h => h.Contains(".jpg")).ToArray();
foreach(string a in hrefs)
{
using (WebClient client = new WebClient())
{
client.DownloadFile(a, #"C:\Images\file" + count + ".jpg");
}
count ++;
pagesorimages = true;
backgroundWorker1.ReportProgress(0, count);
}
//ProcessNextLink();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
ProcessNextLink();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (pagesorimages == false)
{
label1.Text = e.UserState.ToString();
}
if (pagesorimages == true)
{
label2.Text = e.UserState.ToString();
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
}
}
The exception is on the second ReportProgress:
backgroundWorker1.ReportProgress(0, count);
This operation has already had OperationCompleted called on it and further calls are illegal
What i want to do is to report first the current page number in this case it's 1 to label1.
And then to report the number of downloaded images in this page to label2.
Then to move to the next page with the method ProcessNextLink(); and again report the page number it should be 2 and then to report the number of images downloaded in page 2.
But i'm getting this exception already on the first page.
It was working fine without the backgroundworker in the event webBrowser1_DocumentCompleted i called ProcessNextLink(); in the bottom and it was working fine. But with the backgroundworker it's not working.

Spell checker in a WPF RichTextBox

I have created a RichTextBox text editor as a c# Form application solution. I have added a WPF application to this solution to act as a spellchecker. Basically, when I run the spell checker the contents of the RichTextBox are copied to a WPF RichTextBox in the WPF application which I have configured to look like a spell check dialog. I have included a ListBox which displays the spelling error suggestions and buttons that allow the user to ignore errors or change if one of the suggestions are clicked.
The main routine loops through the text in the RichTextBox until it finds a spelling error. The user then has the option to ignore by clicking a button that calls EditingCommands.IgnoreSpellingError or change by clicking a button that calls EditingCommands.CorrectSpellingError. Currently I am using another button to then re-cycle through the RichTextBox to find the next spelling error.
Ideally what I would like to happen is, for example, when the ignore button is clicked, the EditingCommands.IgnoreSpellingError is called and then the main routine is run immediately after, like so:
private void button3_Click(object sender, RoutedEventArgs e)
{
button3.Command = EditingCommands.IgnoreSpellingError;
button3.CommandTarget = richTextBox1;
spellCheckWords();
}
However, this does not work as the RichTextBox seems to go out of synchronisation with the spell checker. It's as if the form or the RichTextBox are not refreshing properly. Just to re-iterate, if I use a separate button to re-run the main routine then it works ok.
The full code is below.
Any help would be appreciated.
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
richTextBox1.SpellCheck.IsEnabled = true;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
richTextBox1.Paste();
richTextBox1.ContextMenu = GetContextMenu();
spellCheckWords();
}
private static int chrPos = 0;
private void spellCheckWords()
{
SpellingError spellingError;
TextRange spellErrorRange;
TextPointer start_pointer, end_pointer;
richTextBox1.ContextMenu = GetContextMenu();
richTextBox1.SelectAll();
int txtLen = richTextBox1.Selection.Text.Length;
bool noSpellingErrors = true; ;
for (int i = chrPos; i < txtLen; i++)
{
start_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition
(LogicalDirection.Forward).GetPositionAtOffset(i, LogicalDirection.Forward);
spellingError = richTextBox1.GetSpellingError(start_pointer);
if (spellingError != null)
{
spellErrorRange = richTextBox1.GetSpellingErrorRange(start_pointer);
int errRange = spellErrorRange.Text.Length;
textBox1.Text = spellErrorRange.Text;
noSpellingErrors = true;
string textRun = start_pointer.GetTextInRun(LogicalDirection.Forward);
string trimmedString = string.Empty;
end_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition
(LogicalDirection.Forward).GetPositionAtOffset(i + errRange, LogicalDirection.Forward);
richTextBox1.Selection.Select(start_pointer, start_pointer);
richTextBox1.Focus();
Rect screenPos = richTextBox1.Selection.Start.GetCharacterRect(LogicalDirection.Forward);
double offset = screenPos.Top + richTextBox1.VerticalOffset;
richTextBox1.ScrollToVerticalOffset(offset - richTextBox1.ActualHeight / 2);
listBox1.Items.Clear();
foreach (string str in spellingError.Suggestions)
{
listBox1.Items.Add(str);
}
//chrPos = i + errRange + 1;
return;
}
}
if (noSpellingErrors == true)
{
textBox1.Text = "No spelling Errors";
listBox1.Items.Clear();
button2.IsEnabled = false;
button3.IsEnabled = false;
button4.IsEnabled = false;
button6.IsEnabled = false;
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
richTextBox1.SelectAll();
richTextBox1.Copy();
richTextBox1.Document.Blocks.Clear();
richTextBox1.SpellCheck.IsEnabled = false;
this.Close();
}
private ContextMenu GetContextMenu()
{
return null;
}
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listBox1.SelectedItem != null)
textBox1.Text = listBox1.SelectedItem.ToString();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
button2.Command = EditingCommands.CorrectSpellingError;
button2.CommandParameter = textBox1.Text;
button2.CommandTarget = richTextBox1;
spellCheckWords();
}
private void button3_Click(object sender, RoutedEventArgs e)
{
button3.Command = EditingCommands.IgnoreSpellingError;
button3.CommandTarget = richTextBox1;
spellCheckWords();
}
private void button4_Click(object sender, RoutedEventArgs e)
{
spellCheckWords();
}
}
}
After a while i got your problem^^ (i think) and it is easy to fix.
In you Button-Click-events you set the command of the button and the parameters and then execute spellCheckWords. But the actual command is executed AFTER the code has leaved the method.
Which means, spellCheckWords() is executed BEFORE IgnoreSpellingError.
Change your code to this:
private void button2_Click(object sender, RoutedEventArgs e)
{
EditingCommands.CorrectSpellingError.Execute(textBox1.Text, richTextBox1);
spellCheckWords();
}
private void button3_Click(object sender, RoutedEventArgs e)
{
EditingCommands.IgnoreSpellingError.Execute(null, richTextBox1);
spellCheckWords();
}
This will execute the command first and then the spellcheck again.

Saving values from datagridview

I am new to c#. I have been trying to add values from my datagrid to mysql but in vain and i really need your help. The values are automatically generated after a time interval of 1 sec and i need to insert them to the mysql in the same time interval. Here are the codes.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace BLIND_SHOPPING_SYSTEM
{
public partial class Form2 : Form
{
private DataTable m_TagDataTable = new DataTable("Tag List");
long passiveID = 0;
public Form2()
{
InitializeComponent();
this.m_TagDataTable.Columns.Add("TagID");
}
private void btn_GenerateID_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
public void timer1_Tick(object sender, EventArgs e)
{
if (passiveID < 10)
{
passiveID = passiveID + 1;
//listBox1.Items.Add(passiveID);
//this.m_TagDataTable.Columns.Add("TagID");
this.dataGridView1.DataSource = m_TagDataTable;
DataRow dr = m_TagDataTable.NewRow();
dr["TagID"] = passiveID;
m_TagDataTable.Rows.Add(dr);
}
else
// Application.Exit();
Console.ReadLine();
}
private void btn_Stop_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
}
}
Please kindly help me.
You probably want to use a DataTableAdapter and specify the Update command, see here for some examples ;) http://msdn.microsoft.com/en-us/library/ms233819(v=vs.80).aspx

Categories