|
hi guys, so I changed my code and the problem in that particular place is solved but reemerging elsewhere. So I have two buttons now. One button (button1) is used to open and close the port, second (button3) is used to start filling up text boxes from the serial port. What is happening is that when I open the port and click start it starts filling the text boxes fine. but when I click stop (button3) the command to clear the text boxes is not getting executed. Also subsequently when I close the port (button1) and reopen it (button1 again) then click button 3 again to start filling the text boxes again, the same error repeats (index is out of bounds of the array) . Below is my new code.
private bool isFirstLine = true;
void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
try
{
string dataLine = serialPort1.ReadLine();
if (dataLine == null || dataLine.Trim().Length == 0)
{
return;
}
if (isFirstLine)
{
isFirstLine = false;
return;
}
string[] dataValues = dataLine.Split('\t');
this.Invoke((MethodInvoker)delegate
{
textBox2.Text = dataValues[0];
textBox3.Text = dataValues[1];
textBox4.Text = dataValues[2];
textBox5.Text = dataValues[3];
textBox6.Text = dataValues[4];
textBox7.Text = dataValues[5];
textBox8.Text = dataValues[6];
textBox9.Text = dataValues[7];
textBox10.Text = dataValues[8];
textBox11.Text = dataValues[9];
textBox12.Text = dataValues[10];
textBox13.Text = dataValues[11];
textBox14.Text = dataValues[12];
textBox15.Text = dataValues[13];
textBox16.Text = dataValues[14];
textBox17.Text = dataValues[15];
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ClearTextBoxes()
{
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
textBox7.Text = "";
textBox8.Text = "";
textBox9.Text = "";
textBox10.Text = "";
textBox11.Text = "";
textBox12.Text = "";
textBox13.Text = "";
textBox14.Text = "";
textBox15.Text = "";
textBox16.Text = "";
textBox17.Text = "";
}
private bool isReadingData = false;
private void button3_Click(object sender, EventArgs e)
{
try
{
if (serialPort1.IsOpen)
{
if (!isReadingData)
{
serialPort1.WriteLine("1");
serialPort1.DataReceived += DataReceivedHandler;
isReadingData = true;
button3.Text = "STOP";
button1.Enabled = false;
button1.Visible = false;
}
else
{
serialPort1.WriteLine("0");
serialPort1.DataReceived -= DataReceivedHandler;
isReadingData = false;
button3.Text = "START";
button1.Enabled = true;
button1.Visible = true;
ClearTextBoxes();
}
}
else
{
MessageBox.Show("Error : Port needs to be open or wrong port selected!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button1_Click(object sender, EventArgs e)
{
if(serialPort1.IsOpen)
{
PortClosing();
button1.Text = "Open";
ClearTextBoxes();
button3.Visible = false;
}
else
{
PortOpening();
button1.Text = "Close";
button3.Visible = true;
}
}
modified 21-Nov-23 2:41am.
|
|
|
|
|
As suggested, you need to learn how to debug the code by using the debugger.
That will allow you to step through the lines.
Kshitij Bali wrote: index is out of bounds of the array
I think this was already suggested....
This is accessing an array 'dataValues[15]'
The error occurs when the array is NOT that big.
You are assuming it is that size. It isn't. So you need to check. As suggested the results are probably coming in pieces and not all at once. Or only some is coming.
|
|
|
|
|
I'm trying to populate a combobox with a column in a SQLite database table. Im using an Absolute path in my connection string but Im getting an Error that the table doesn't exist. Ive read through other posts and still cant resolve the problem. Here is my code.
public Form1()
{
InitializeComponent();
if (File.Exists(@"R:\TEOP\Tracker\Tracker.db"))
{
SQLiteConnection conn;
conn = new SQLiteConnection("Data Source=R:\\TEOP\\Tracker\\Tracker.db,version=3;");
conn.Open();
SQLiteCommand cmd;
cmd = conn.CreateCommand();
cmd.CommandText = @"SELECT IncidentName FROM Incident;";
var dr = cmd.ExecuteReader();
while (dr.Read())
{
IncidentCombo.Items.Add(dr["IncidentName"]);
}
}
}
Ive checked permissions and path. My query works in the database browser.
|
|
|
|
|
In problem posts like this, always copy'n'paste the exact error message.
If the message indeed says your table doesn't exist, it has nothing to do with the connection string. It's telling you don't have a table called 'Incident' in your database. Check the spelling of the table name in your query and carefully compare to the table name in the database.
|
|
|
|
|
NOTE: DISCLAIMER: I have no experience with SQLite! This is just a shot in the dark from an ignorant non-expert:
I tried to look up examples of SQL use, and saw them use a semicolon rather than a comma before 'version=3;'
I also saw that opening a non-existing database will created one by the given name.
So, if the entire string 'R:\\TEOP\\Tracker\\Tracker.db,version=3' is take as a database name, then you are opening a new, empty database, which obviously doesn't have an 'Incident' table.
(I must admit that I am surprised if a database can be named R:\\TEOP\\Tracker\\Tracker.db,version=3, so this may be a completely wrong track to follow!)
|
|
|
|
|
Thank you that was the problem ....A typing error replacing the "," with a ";" was the problem. Syntax is a killer at times!....lol
|
|
|
|
|
Nice catch. I missed that one.
|
|
|
|
|
Just seen this example of C# 12 on Reddit:
public double GPA => grades switch
{
[] => 4.0,
[var grade] => grade,
[.. var all] => all.Average()
}; Seems innocuous enough, but there is a subtle problem: if the array contains more than one element, the property will allocate a copy of the entire array simply to pass to the Average method.
SharpLab[^]:
public double GPA
{
get
{
double[] array = <grades>P;
if (array != null)
{
int num = array.Length;
if (num != 0)
{
if (num == 1)
{
return array[0];
}
double[] subArray = RuntimeHelpers.GetSubArray(array, new Range(new Index(0), new Index(0, true)));
return Enumerable.Average(subArray);
}
return 4.0;
}
<PrivateImplementationDetails>.ThrowSwitchExpressionException(array);
double result = default(double);
return result;
}
} NB: The RuntimeHelpers.GetSubArray method[^] has no check to see if it's returning the entire array; it always creates a copy.
It's simple enough to fix:
public double GPA => grades switch
{
[] => 4.0,
[var grade] => grade,
[..] all => all.Average()
}; SharpLab[^]
public double GPA
{
get
{
double[] array = <grades>P;
if (array != null)
{
int num = array.Length;
if (num != 0)
{
if (num == 1)
{
return array[0];
}
return Enumerable.Average(array);
}
return 4.0;
}
<PrivateImplementationDetails>.ThrowSwitchExpressionException(array);
double result = default(double);
return result;
}
} But good luck spotting the difference in a code review, or explaining to anyone who hasn't spent time spelunking the BCL source repository why [..] all is better than [.. var all] !
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I think I'll stick with C, or maybe go back to COBOL.
|
|
|
|
|
I have seen two different developers use a foreach() on a hash. To do a look up. So it turns the hash into a list of key-value pairs then searches that list. Naturally completely obliviating the point of the hash.
Surprised me so much that now it is something I explicitly look for.
|
|
|
|
|
what should i do now when i run the program and it has this error : "
Exception from HRESULT: 0x800A03EC
"
|
|
|
|
|
You could start by asking Google what the error code means. Then go back to your code, to the line where the error is produced, and try to work out what is wrong with your code or the data it is working on.
|
|
|
|
|
Your error seems to be excel related, you did however posted a one liner and expected the world to mind read what you meant.
I googled the error and it popped up with multiple solutions - Save me from this error[^]
and by selecting the first solution on SO, easy to fix - My error is fixed![^]
|
|
|
|
|
I am new to asp.net core. I have a form which is generated dynamically. I want the validation error message to be "The value must be numeric" instead I get "The value 'a' is invalid" when I submit the form.
Here is my View Model:
[RegularExpression("^[0-9]*$", ErrorMessage = "The value must be numeric")]
public List<int> Units_Service { get; set; }
Here is my form code:
for (int i = 0; i < Model.Workload_Category_Name.Count; i++)
{
<div class="row">
<div class="col-md-3">
<b></u>@Html.DisplayFor(model => model.Workload_Category_Name[i])</u> </b>
</div>
<div class="col-md-4">
@Html.TextBoxFor(model => model.Units_Service[i], new { style = "width: 15%", MaskedTextBox = "9999" })
@Html.ValidationMessageFor(model => model.Units_Service[i])
</div>
</div>
}
Despite the fact, I have put the custom error message in my View Model as shown above, I keep getting the default message "The value '' is invalid". Please what is the solution to this kind of scenario ?
|
|
|
|
|
The problem is, you're validating the Units_Service property, not the individual items within it.
And applying a regular expression validation to anything other than a string property makes no sense.
Probably the simplest option would be to create a viewmodel for each item in the list - for example:
public class UnitsServiceViewModel
{
[Required(ErrorMessage = "You must enter a value.")]
[RegularExpression("^[0-9]*$", ErrorMessage = "The value must be numeric.")]
public string Value { get; set; }
}
public class OuterViewModel
{
public List<UnitsServiceViewModel> Units_Service { get; set; }
internal List<int> Units_Service_Parsed
{
get
{
if (Units_Service is null) return null;
List<int> value = new(Units_Service.Count);
foreach (UnitsServiceViewModel vm in Units_Service)
{
int.TryParse(vm.Value, out int i);
value.Add(i);
}
return value;
}
set
{
if (value is null)
{
Units_Service = null;
}
else
{
List<UnitsServiceViewModel> list = new(value.Count);
foreach (int i in value)
{
list.Add(new() { Value = i.ToString() });
}
Units_Service = list;
}
}
}
}
@for (int i = 0; i < Model.Units_Service.Count; i++)
{
<div class="row">
<div class="col-md-3">
@Html.LabelFor(model => model.Units_Service[i].Value, Model.Workload_Category_Name[i])
</div>
<div class="col-md-4">
@Html.TextBoxFor(model => model.Units_Service[i].Value, new { style = "width: 15%", MaskedTextBox = "9999", inputmode = "numeric" })
@Html.ValidationMessageFor(model => model.Units_Service[i].Value)
</div>
</div>
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks Richard. Your answer works perfect
|
|
|
|
|
Fokwa Divine wrote: "^[0-9]*$"
Note that this (and in the corrected code) allows for an empty string.
You probably want the following
^[0-9]+$
You might also want to check for limits. So is '0' a correct value? Is '1000000000'?
|
|
|
|
|
Thanks for your input jschell
Yes, I am checking for limit and '0' is a correct value per requirement
|
|
|
|
|
function to extract the nibbles from a given byte.
|
|
|
|
|
You seem to have mistaken this site for a search engine or AI chatbot.
We're more than happy to help you with problems with code you have written. But nobody here is going to do your work for you, even if you had asked politely.
Also, you've posted in the C# forum, but your message subject suggests you're working in C. Despite the similar names, those are to completely different languages. A solution for one probably won't work in the other.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
This is easily accomplished using masking and bit-shifting. Do some research on how these work and you should be able to do it, and learn something interesting along the way.
|
|
|
|
|
I have a winform project where i am using web browser control which load a site. the site has many tabular data which is a html table. user will select large text from web browser control using their mouse. the select may have many data including multiple tabular data which is nothing but a html table.
I know how to get text from selection. this is sample code which return text.
private string GetSelectedText()
{
dynamic document = webBrowser1.Document.DomDocument;
dynamic selection = document.selection;
dynamic text = selection.createRange().text;
return (string)text;
}
But i need html of selected area on web browser control programmatically. i use a code sample which suppose to return html of selected portion of web page loaded into web browser control.....but no luck.
here i am sharing that code which not working as expected. please see my code and tell me how could grab the html content from web browser control of large selection ?
here is the code which is not working.
<pre>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace HtmlTableParser
{
public partial class Form2 : Form
{
private WebBrowser webBrowser1;
public Form2()
{
InitializeComponent();
Button btn = new Button();
btn.Text = "Test";
btn.Click += button1_Click;
this.Controls.Add(btn);
var panel = new Panel();
panel.Top = btn.Height + 2;
panel.Height = this.ClientSize.Height - btn.Height + 2;
panel.Width = this.ClientSize.Width;
panel.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
webBrowser1 = new WebBrowser();
webBrowser1.Dock = DockStyle.Fill;
webBrowser1.Url = new Uri("https://www.sec.gov/Archives/edgar/data/1108134/000110813423000018/bhlb-20230630.htm");
panel.Controls.Add(webBrowser1);
this.Controls.Add(panel);
}
private void button1_Click(object sender, EventArgs e)
{
TestSelection();
TestAllTable();
}
private void TestSelection()
{
var domdoc = this.webBrowser1.Document.DomDocument as mshtml.IHTMLDocument2;
var sel = domdoc.selection;
var range = sel.createRange();
var trange = range as mshtml.IHTMLTxtRange;
var table = GetParentTable(trange.parentElement());
if (table == null)
{
var startPointRange = trange.duplicate();
startPointRange.setEndPoint("EndToStart", trange);
var startPointTable = GetParentTable(startPointRange.parentElement());
var endPointRange = trange.duplicate();
startPointRange.setEndPoint("StartToEnd", trange);
var endPointTable = GetParentTable(endPointRange.parentElement());
if (startPointTable != null)
{
table = startPointTable;
}
else if (endPointTable != null)
{
table = endPointTable;
}
else
{
MessageBox.Show("Selection is not in Table");
return;
}
}
var tableData = TableData.GetTableData(table);
System.Diagnostics.Debug.WriteLine(tableData.ToString());
}
private mshtml.IHTMLTable GetParentTable(mshtml.IHTMLElement element)
{
var parent = element;
while (parent != null)
{
if (parent is mshtml.IHTMLTable table)
{
return table;
}
parent = parent.parentElement;
}
return null;
}
private void TestAllTable()
{
var domdoc = this.webBrowser1.Document.DomDocument as mshtml.HTMLDocument;
foreach (var table in domdoc.getElementsByTagName("table").OfType<mshtml.IHTMLTable>())
{
var tableData = TableData.GetTableData(table);
System.Diagnostics.Debug.WriteLine(tableData.ToString());
System.Diagnostics.Debug.WriteLine(new string('=', 20));
}
}
}
class TableData
{
public static TableData GetTableData(mshtml.IHTMLTable table)
{
TableData tableData = new TableData();
foreach (var tableRow in table.rows.OfType<mshtml.IHTMLTableRow>())
{
RowData rowdata = new RowData();
foreach (var tablecell in tableRow.cells.OfType<mshtml.HTMLTableCell>())
{
CellData cell = new CellData();
cell.Text = tablecell.innerText;
cell.RowSpan = tablecell.rowSpan;
cell.ColSpan = tablecell.colSpan;
rowdata.Add(cell);
}
tableData.Rows.Add(rowdata);
}
return tableData;
}
public List<RowData> Rows { get; } = new List<RowData>();
public override string ToString()
{
System.Text.StringBuilder sb = new StringBuilder();
foreach (var row in this.Rows)
{
sb.AppendLine(row.ToString());
}
return sb.ToString();
}
}
class RowData : List<CellData>
{
public override string ToString()
{
return string.Join("\t", this.Select(cell => cell.Text + new string('\t', cell.ColSpan)));
}
}
class CellData
{
public string Text { get; set; }
public int ColSpan { get; set; }
public int RowSpan { get; set; }
public override string ToString() => Text;
}
}
Here i am pasting a image which show how user will selected the portion of page.
screen shot
It is my request that for last few days i have tried many approach to get html of selection portion from web browser control....but not succeeded. please some one help me with right approach.
Thanks
|
|
|
|
|
No new code should be written today using the ancient WebBrowser control. It's an instance of Internet Explorer, and unless you edit the registry on every single computer where your code runs, it's stuck in IE7-compatability mode.
Instead, use a modern control such as WebView2[^] (Edge), CefSharp[^] (Chrome), or GeckoFX[^] (Firefox).
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
WebView not available for .net core 6 winform project. can you suggest any browser control which i can use
.net core 6 winform project ?
Thanks
|
|
|
|
|