|
This is an English-language site. Please post all questions in English.
If you don't speak English, Google Translate should get you close enough.
Este é um site em inglês. Poste todas as perguntas em inglês.
Se você não fala inglês, o Google Translate deve aproximá-lo o suficiente.
Quote: Talk to people, good afternoon.
I'm having a hard time getting my strings from my checkedlistbox to do an update on my system.
my real scenario is this, I can do the insert through the checkedlistbox by concatenating more than one string and storing it in a table called students and storing my selected strings in the activity column.
When I do the update I can not get more than one string to update my checklistbox, it returns only one selected when I click on my button to update the information.
follow the code to understand better.
this is my code to do the update through ArrayLisyt where I get my textbox, and comboBox
Quote: This is my class where the parameters are to perform the update.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I get an 'object reference not set to an instance of an object' error on the ' if (xmlResponse.SelectSingleNode("/Response/Code").InnerText != "")' line. I know that is a vague error and If someone can see what the problem based off the code. I would also like to know where I can go to or how to get a more specific error message if possible. And also I know there is an xmlResolver that can be set to null that can be used but not sure how to use it in this code.
using System;
namespace Shipment_WS_Test_App
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
try
{
string flg = string.Empty;
while (flg != "q")
{
System.Text.StringBuilder request = new System.Text.StringBuilder();
saia.shipment.Shipment shipment = new saia.shipment.Shipment();
shipment.Timeout = 120000;
request.Append("<GetByProNumber>");
request.Append("<UserID>userid</UserID>");
request.Append("<Password>password</Password>");
request.Append("<TestMode>N</TestMode>");
request.Append("<ProNumber>983579110</ProNumber>");
request.Append("</GetByProNumber>");
string xmlreq = "<AmazonTrackingRequest xmlns:xsi=\"www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"AmazonTrackingRequest.xsd\"><Validation><UserID>AMZN</UserID><Password>12345</Password></Validation><APIVersion>4.0</APIVersion><TrackingNumber>123456789</TrackingNumber></AmazonTrackingRequest> ";
string response = shipment.ProcessXML(xmlreq);
System.Xml.XmlDocument xmlResponse = new System.Xml.XmlDocument();
xmlResponse.LoadXml(response);
if (xmlResponse.SelectSingleNode("/Response/Code").InnerText != "")
{
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Code").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Element").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Fault").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Message").InnerText);
}
else
{
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/AccountNumber").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/Address1").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/Address2").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/City").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/State").InnerText);
System.Console.WriteLine(xmlResponse.SelectSingleNode("/Response/Consignee/Zipcode").InnerText);
);
}
shipment.Dispose();
request = null;
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
}
}
|
|
|
|
|
This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.
Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.
We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!
Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.
But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Griff has given you good advice. I will say that the reason you are seeing this error is probably because of a fundamental assumption you're making here - that you have /Response/Code as a single node. If you retrieve this into a separate variable, I bet you'll see that you don't actually have this as a response. BTW - quick hint, if you wrap the instantiation of shipment into a using statement, you'll automatically get a Dispose on it, so you won't need to worry about having to manually call Dispose yourself.
This space for rent
|
|
|
|
|
Since it looks like you're writing new code, rather than maintaining existing code, you might want to consider using LINQ to XML instead:
LINQ to XML Overview (C#) | Microsoft Docs[^]
using System;
using System.Xml.Linq;
using System.Xml.XPath;
namespace Shipment_WS_Test_App
{
static class Class1
{
private static readonly XNamespace XsiNamespace = "www.w3.org/2001/XMLSchema-instance";
[STAThread]
static void Main(string[] args)
{
try
{
using (var shipment = new saia.shipment.Shipment())
{
shipment.Timeout = 120000;
var request = new XDocument(
new XElement("AmazonTrackingRequest",
new XAttribute(XNamespace.Xmlns + "xsi", XsiNamespace),
new XAttribute(XsiNamespace + "noNamespaceSchemaLocation", "AmazonTrackingRequest.xsd"),
new XElement("Validation",
new XElement("UserID", "AMZN"),
new XElement("Password", "12345")
),
new XElement("APIVersion", "4.0"),
new XElement("TrackingNumber", "123456789")
)
);
string response = shipment.ProcessXML(request.ToString());
if (string.IsNullOrEmpty(response))
{
Console.WriteLine("No response.");
}
else
{
XDocument xmlResponse = XDocument.Parse(response);
if (xmlResponse.Root == null)
{
Console.WriteLine("No response. ({0})", response);
}
else
{
XElement responseNode = xmlResponse.Root.Element("Response");
if (responseNode == null)
{
Console.WriteLine("Response element not found. ({0})", xmlResponse);
}
else if (!string.IsNullOrEmpty((string)responseNode.Element("Code")))
{
Console.WriteLine(responseNode.Element("Code"));
Console.WriteLine(responseNode.Element("Element"));
Console.WriteLine(responseNode.Element("Fault"));
Console.WriteLine(responseNode.Element("Message"));
}
else
{
XElement consigneeNode = responseNode.Element("Consignee");
if (consigneeNode == null)
{
Console.WriteLine("Consignee element not found. ({0})", responseNode);
}
else
{
Console.WriteLine(consigneeNode.Element("AccountNumber"));
Console.WriteLine(consigneeNode.Element("Address1"));
Console.WriteLine(consigneeNode.Element("Address2"));
Console.WriteLine(consigneeNode.Element("City"));
Console.WriteLine(consigneeNode.Element("State"));
Console.WriteLine(consigneeNode.Element("Zipcode"));
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
when i tried to disable and enable the USB COM port using DecriptionName from setupapi.dll using this am disabling and enabling the USB port, it's working fine now Enable and Disable, but the problem is when i disabled the COM port initially after once i closed the Application and tried to Enable the same COM port again its not Enabling the COM port i don't know why..
I don't know how to solve that problem.
|
|
|
|
|
How do you disable and enable the device (which function(s) do you use)?
Does the function(s) return some kind of error code?
If yes, what is the code?
Just out of interest: Why do you want to disable a device?
|
|
|
|
|
Please don't post things in multiple places: it duplicates work and that annoys people.
You already have this in QA, so leave it there!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
This was posted first and I just wrote a comment about reposting at the QA post.
|
|
|
|
|
Instead of reposting at QA you should edit your question here or at least answer to provide the additional requested information.
However, in your QA post you had initially some code but removed that. It won't work as shown in that code. While you can store a SP_DEVINFO_DATA returned from SetupDiEnumDeviceInfo in an XML file and read it back, that can't be used for further SetupDI functions when using a different HDEVINFO .
Instead, enumerate again (e.g. using the GUID) to find the disabled device and get a new SP_DEVINFO_DATA structure.
|
|
|
|
|
hi. how can i binding datagridview columns with entity framework that
AutoGenerateColumns=false .
<pre>var book = context.Books
.Where(b => b.ISBN == txtISBN.Text).ToList();
dataGridViewBook.DataSource = book;
|
|
|
|
|
|
Hi,
I have a program that gives me all result i search and put them in listbox.
My first problem is that it need 1-2 second when i start to search to find me a items.
Second problem is when i update items, it writes in ini file but gives me error when i try to update a listbox with edited item.
<pre>using System;
using System.Windows.Forms;
using IniParser;
using IniParser.Model;
using System.Collections.Generic;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public string myFilePath;
public string searchItem;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
searchBtn.Enabled = false;
writeIniBtn.Enabled = false;
saveBtn.Enabled = false;
AcceptButton = this.searchBtn;
}
private void openIniBtn_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = "c:\\";
openFile.Filter = "INI files (*.ini)|*.ini";
openFile.Title = "Select a INI file for edit";
if (openFile.ShowDialog() == DialogResult.OK)
{
myFilePath = openFile.FileName;
searchBtn.Enabled = true;
writeIniBtn.Enabled = true;
saveBtn.Enabled = true;
openIniBtn.Enabled = false;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> selectedItems = new List<string>();
string item = listBox1.SelectedItem.ToString();
if (!selectedItems.Contains(item))
{
selectedItems.Add(item);
}
foreach (string i in listBox1.SelectedItems)
{
itemIdTxt.Text = i.Split('[', ']')[1];
nameInput.Text = i.Split('[', ']')[2];
}
}
private void searchBtn_Click(object sender, EventArgs e)
{
var searchItem = searchInput.Text;
var parser = new FileIniDataParser();
parser.Parser.Configuration.AllowDuplicateKeys = true;
IniData data = parser.ReadFile(myFilePath);
listBox1.Items.Clear();
searchItem = searchInput.Text;
foreach (var item in data.Sections)
{
if (item.Keys["1"].IndexOf(searchItem, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
var foundedItems = ($"[{item.SectionName}] {item.Keys["1"]}");
ListBox list = new ListBox();
listBox1.Items.Add(foundedItems);
}
}
}
private void saveBtn_Click(object sender, EventArgs e)
{
var id = itemIdTxt.Text;
var name = nameInput.Text;
var parser = new FileIniDataParser();
parser.Parser.Configuration.AllowDuplicateKeys = true;
IniData data = parser.ReadFile(myFilePath);
data[id]["1"] = name;
parser.WriteFile(myFilePath, data);
string index = listBox1.SelectedItem.ToString();
listBox1.Items.Remove(index);
listBox1.Items.Add(name);
}
}
}
|
|
|
|
|
What is the error, and where does it occur?
|
|
|
|
|
I get error on this line
string item = listBox1.SelectedItem.ToString();
Error is :
Exception thrown: 'System.NullReferenceException' in WindowsFormsApp1.exe
System.Windows.Forms.ListBox.SelectedItem.**get** returned null.
I open a file, search for item, i get list with founded results.
When i click on item it is show i set it with this 2 lines
itemIdTxt.Text = i.Split('[', ']')[1];
nameInput.Text = i.Split('[', ']')[2];
And when i edit it in nameInput and press Save button it write in ini file and throw me an error.
So problem is in this i supose, when i try to update edited item
string index = listBox1.SelectedItem.ToString();
listBox1.Items.Remove(index);
listBox1.Items.Add(name);
|
|
|
|
|
A listbox may have no item selected. You can check that with ListBox.SelectedIndex which returns -1 if no item is selected.
In your last code snippet you are removing the selected item and adding a new one. As a result, there will be no item selected (removing the selected item will remove also the selection).
Note also that using ListBox.Items.RemoveAt passing the index is better (faster) than searching for an item by the string:
int index = listBox1.SelectedIndex;
if (index >= 0)
listBox1.Items.RemoveAt(index);
|
|
|
|
|
https://image.prntscr.com/image/SPNK0IBeSiC2dy7kG9W0kw.png
Here is a image for better view and understand of code.
As i imagine the program works is to select a item, split it into 2 sections SECTION and KEY because i need both to update a ini file where i need to use section name to write to ini file as you can see here
<pre lang="c#">
var id = itemIdTxt.Text; // read id
var name = nameInput.Text; // read name
// write to ini file
var parser = new FileIniDataParser();
parser.Parser.Configuration.AllowDuplicateKeys = true;
IniData data = parser.ReadFile(myFilePath);
data[id]["1"] = name;
parser.WriteFile(myFilePath, data);
</pre>
|
|
|
|
|
But that is not related to my post where I tried to explain while your code fails when trying to access selected item(s) when nothing is selected.
Depending on what you want to do (replace), you might search for the old item, update the selection programmatically to ensure that it is always set (to what should be set), or track the index of the item to be replaced to be used in the button handler.
|
|
|
|
|
that seems to be so complicated for beginner.
|
|
|
|
|
Hi, i have a problem with setting a file path to a public variable.
So, what my code must do :
- open file
- set full path to a file so i can read it in another function
- in other function open ini file for reading
but i cant get a file path to it
Here is a code ;
using System;
using System.Windows.Forms;
using IniParser;
using IniParser.Model;
using System.Collections.Generic;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public string myFilePath;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
searchBtn.Enabled = false;
writeIniBtn.Enabled = false;
saveBtn.Enabled = false;
}
private void openIniBtn_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = "c:\\";
openFile.Filter = "INI files (*.ini)|*.ini";
openFile.Title = "Select a INI file for edit";
if (openFile.ShowDialog() == DialogResult.OK)
{
string myFilePath = openFile.FileName;
searchBtn.Enabled = true;
writeIniBtn.Enabled = true;
saveBtn.Enabled = true;
openIniBtn.Enabled = false;
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count != 0)
{
ListViewItem item = listView1.SelectedItems[0];
string output = item.Text.Split('[', ']')[1];
string outputt = item.Text.Split('[', ']')[2];
itemIdTxt.Text = output.ToString();
nameInput.Text = outputt.ToString();
}
}
private void searchBtn_Click(object sender, EventArgs e)
{
MessageBox.Show("my file path : " + myFilePath);
|
|
|
|
|
That's because you've hidden the field with a local variable:
public string myFilePath;
private void openIniBtn_Click(object sender, EventArgs e)
{
...
string myFilePath = openFile.FileName;
...
}
Remove the local variable, and use the field instead:
private void openIniBtn_Click(object sender, EventArgs e)
{
...
myFilePath = openFile.FileName;
...
}
If you want to be absolutely safe, you can even prefix the field name with this. to ensure that it uses the field and not a local variable:
private void openIniBtn_Click(object sender, EventArgs e)
{
...
this.myFilePath = openFile.FileName;
...
}
Scopes | Basic concepts | C# Language Reference | Microsoft Docs[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks man this solved my problem.
|
|
|
|
|
Is there a known API to Google Images[^] so that it is possible to use it automatically with local files?
|
|
|
|
|
Try the Google developers website.
|
|
|
|
|
I hope someone can help me. I develop my first C# WPF Program and I need an input control for IP Address. To my big surprise there isn't a control for this which I think is pretty strange. In C++ I have something like that.
Okay so far I have read I could use a masked textbox from the extended wpf toolkit. But I have 2 problems with that:
First of all when I use a mask like 000.000.000.000 and someone wants to enter an address like 192.168.1.1 I would get 192.168.001.001 But I don't want to see leading zeros
the second problem is that someone could enter an address like 500.300.400.800. How can I handle this?
|
|
|
|