|
i have this code
var Result = from x in db.vams
join y in db.ghests
on new { X1 = x.code_sabt } equals new { X1 = y.code_sabt }
where y.code_vam == (from z in db.vams where z.code_sabt == myuser select z.row_codevam).Max()
group y by x.row_codevam into g
select new
{
sum_ghest = g.Sum(k=>k.price),
i need-----> x.colimns :( :( :(
};
how can i access to
db.vams columns in the select new part??????
|
|
|
|
|
I am having a STUPID amount of trouble with this. Just when I think I have it figured out - I don't. One thing I have found is that events seem to find a seemingly random order and nested events just refuse the way you expect them to and do not trigger in the order you might expect.
Basically : I have XAML form. On this form I have (among other controls), several bound drop down list controls. The first of these is not dependent on any other, the contents of the second drop down list is dependent on the selected value of the first, the third is dependent on the selection in the second and so on.
Problem 1 : The list contents vary in size depending on other form values. This means that when I am creating a list it sometimes throws an index out of bounds error if the previous index was 4 and the new list only contains 2 entries
Problem 2 : I keep getting stuck in loops. Updating the drop list boxes also forces a property change in the selected value which then triggers an update to my list and contents and the cycle continues
Problem 3 : trying to throw OnPropertyChanged at specific points in my code seems to just completely confuse the process with the order that the events are thrown and trapped making very little sense.
Problem 4 : the list goes on.
SO! I arrive here at Code Project. I have make up some sample code and keep it down to an minimum as everything I have done to date seems to be a complete mess. I have also included lines of XAML to show the way the drop down lists are bound to the data.
Part of the issue that is catching me out is the need to also validate and set accordingly the selected property and list contents of the combo boxes. i.e. if the Category is changed I need to update the contents of the Colours combo box and ALSO the selected combo box item. This in turn requires the Shapes combo box and relevant combo box to be validate accordingly.
I am hoping that the below is sufficient to illustrate what is seemingly a simple task. I didn't want to bury this question with a mountain of rubbish code that I have ended up with trying a bunch of experiments to get this to work. I've been working on this ALL DAY today and a fair portion of yesterday so my eyes are getting blurry and productivity has all but left me.
XAML bindings :
<ComboBox Margin="2,2,2,2" BorderThickness="0,0,0,1" Grid.Row="3" Grid.Column="1" ItemsSource="{Binding DataCategoryList}" SelectedIndex="{Binding DataCategory}" DisplayMemberPath="Name" />
<ComboBox Margin="2,2,2,2" BorderThickness="0,0,0,1" Grid.Row="4" Grid.Column="1" ItemsSource="{Binding DataColourList}" SelectedIndex="{Binding DataColour}" DisplayMemberPath="Name"/>
<ComboBox Margin="2,2,2,2" BorderThickness="0,0,0,1" Grid.Row="5" Grid.Column="1" ItemsSource="{Binding DataShapeList}" SelectedIndex="{Binding DataShape}" DisplayMemberPath="Name"/>
C#
public class Base : INotifyPropertyChanged
{
private string _ID;
private string _Name;
public string ID { get { return _ID; } set { _ID = value; OnPropertyChanged( "ID" ); } }
public string Name { get { return _Name; } set { _Name = value; OnPropertyChanged( "Name" ); } }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged( string propertyName )
{
if( PropertyChanged != null )
PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
}
}
public class MyData : INotifyPropertyChanged
{
private Base _Category;
private Base _Colour;
private Base _Shape;
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged( string propertyName )
{
if( PropertyChanged != null )
PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
}
public Base Category
{
get { return _Category; }
set
{
_Category = value;
OnPropertyChanged( "Category" );
}
}
public Base Colour
{
get { return _Colour; }
set
{
_Colour = value;
OnPropertyChanged( "Colour" );
}
}
public Base Shape
{
get { return _Shape; }
set
{
_Shape = value;
OnPropertyChanged( "Shape" );
}
}
}
public class MyWindow : INotifyPropertyChanged
{
private MyData _Data;
public MyData Data { get { return _Data; } set { _Data = value; } }
public MyWindow( ) : base( )
{
Data = new MyData( )
{
Category = new Base( ) { ID = "A", Name = "Category A" },
Colour = new Base( ) { ID = "RD", Name = "Red" },
Shape = new Base( ) { ID = "RND", Name = "Round" },
};
Data.PropertyChanged += Data_PropertyChanged;
}
private void ValidateCategoryChange( string id)
{
Base result = null;
foreach( Base colour in DataColourList )
if( colour.ID == id )
result = colour;
Data.Colour = result ?? DataColourList[ 0 ];
}
private void ValidateColourChange( string id )
{
Base result = null;
foreach( Base shape in DataShapeList )
if( shape.ID == id )
result = shape;
Data.Shape = result ?? DataShapeList[ 0 ];
}
private void Data_PropertyChanged( object sender, PropertyChangedEventArgs e )
{
OnPropertyChanged( String.Format( "Cable{0}", e.PropertyName ) );
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged( string propertyName )
{
if( PropertyChanged != null )
PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
}
public List<Base> BuildCategoryList( )
{
List<Base> result = new List<Base>();
result.Add( new Base( ) { ID = "A", Name = "Category A" } );
result.Add( new Base( ) { ID = "A", Name = "Category B" } );
return result;
}
public List<Base> BuildColourList( string categoryID )
{
List<Base> result = new List<Base>();
if( categoryID == "A" )
{
result.Add( new Base( ) { ID = "RD", Name = "Red" } );
result.Add( new Base( ) { ID = "BL", Name = "Blue" } );
}
else
{
result.Add( new Base( ) { ID = "BK", Name = "Black" } );
result.Add( new Base( ) { ID = "OR", Name = "Green" } );
result.Add( new Base( ) { ID = "RD", Name = "Red" } );
result.Add( new Base( ) { ID = "BL", Name = "Blue" } );
}
return result;
}
public List<Base> BuildShapeList( string colourID )
{
List<Base> result = new List<Base>();
if( colourID == "RD" || colourID == "BK" )
{
result.Add( new Base( ) { ID = "RND", Name = "Round" } );
result.Add( new Base( ) { ID = "SQR", Name = "Square" } );
result.Add( new Base( ) { ID = "TNG", Name = "Triangle" } );
}
else
{
result.Add( new Base( ) { ID = "RCT", Name = "Rectangle" } );
}
return result;
}
public List<Base> DataCategoryList { get; set; }
public int DataCategory
{
get
{
for( int index = 0; index < DataCategoryList.Count; index++ )
if( Data.Category == DataCategoryList[ index ] )
return index;
return -1;
}
set
{
if( value == -1 )
return;
Data.Category.ID = DataCategoryList[ value ].ID;
OnPropertyChanged( "DataCategory" );
DataColourList = BuildColourList( Data.Category.ID );
ValidateCategoryChange( Data.Category.ID );
}
}
public List<Base> DataColourList { get; set; }
public int DataColour
{
get
{
for( int index = 0; index < DataColourList.Count; index++ )
if( Data.Colour == DataColourList[ index ] )
return index;
return -1;
}
set
{
if( value == -1 )
return;
Data.Colour.ID = DataColourList[ value ].ID;
OnPropertyChanged( "DataColour" );
DataShapeList = BuildShapeList( Data.Colour.ID );
ValidateColourChange( Data.Colour.ID );
}
}
public List<Base> DataShapeList { get; set; }
public int DataShape
{
get
{
for( int index = 0; index < DataShapeList.Count; index++ )
if( Data.Category.ID == DataShapeList[ index ].ID )
return index;
return -1;
}
set
{
if( value == -1 )
return;
Data.Category = DataShapeList[ value ];
OnPropertyChanged( "DataShape" );
}
}
}
|
|
|
|
|
I have never used SelectedIndex and suspect that will be the issue, especially when you are changing the content of the bound list. Try changing the binding to SelectedItem.
EG I would have an observablecollection of colours and a selectedcolour object in my viewmodel.
When you rebuild your lists you lose all your selected item/index etc. Try creating a mapping object that you can FILTER instead of rebuilding the lists endlessly.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Talk to people, good afternoon.
I'm having trouble getting my strings from my checklist to do an update on my system.
my real scenario is this, I can do the insertion through the checkbox, concatenating more than one string and storing it in a table called students and storing my selected strings in the activity column.
When I upgrade, I can not get more than one string to refresh my checkbox, it returns only one selected when I click on my button to refresh the information.
follow the code to understand it better.
This is my code to do the update through ArrayLisyt where I get my text box and comboBox
<pre>private void button1_Click(object sender, EventArgs e)
{
SysDBADM obj = new SysDBADM();
ArrayList arr = new ArrayList();
try
{
arr.Add(TB_cod.Text);
arr.Add(TB_nome.Text);
arr.Add(TB_idade.Text);
arr.Add(TB_endereco.Text);
arr.Add(TB_quadra_lote.Text);
arr.Add(MD_telefoneCel.Text);
arr.Add(TB_email.Text);
arr.Add(TB_cidade.Text);
arr.Add(TB_uf.Text);
arr.Add(TB_nomepai.Text);
arr.Add(TB_nomemae.Text);
arr.Add(CB_ativo.Text);
arr.Add(CLB_atividade.Text);
if (obj.Update(arr))
{
TB_cod.Clear();
TB_nome.Clear();
TB_idade.Clear();
TB_endereco.Clear();
TB_quadra_lote.Clear();
MD_telefoneFixo.Clear();
MD_telefoneCel.Clear();
TB_email.Clear();
TB_cidade.Clear();
TB_uf.Clear();
TB_nomepai.Clear();
TB_nomemae.Clear();
CB_ativo.Text = "";
while (CLB_atividade.CheckedItems.Count > 0)
{
CLB_atividade.SetItemChecked(CLB_atividade.CheckedIndices[0],false);
}
MessageBox.Show("Cadastro Atualizado.", "Mensagem do Sistema", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Erro ao Atualizar!", "Mesagem do Sistema", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception erro)
{
MessageBox.Show(erro + "Erro Ocorrido");
}
}
this is my class where are the parameters to perform the update.
public bool Update(ArrayList p_arrUpdate)
{
vsql = "UPDATE alunos SET nome = @nome, idade = @idade, endereco = @endereco, quadra_lote = @quadra_lote, telefone = @telefone, email = @email, cidade = @cidade, uf = @uf, nome_pai = @nome_pai, nome_mae = @nome_mae, situacao = @situacao, atividade = @atividade WHERE id_aluno = @id_aluno";
SqlCommand objcmd = null;
if (this.conectar())
try
{
objcmd = new SqlCommand(vsql, objCon);
objcmd.Parameters.Add(new SqlParameter("@id_aluno", p_arrUpdate[0]));
objcmd.Parameters.Add(new SqlParameter("@nome", p_arrUpdate[1]));
objcmd.Parameters.Add(new SqlParameter("@idade", p_arrUpdate[2]));
objcmd.Parameters.Add(new SqlParameter("@endereco", p_arrUpdate[3]));
objcmd.Parameters.Add(new SqlParameter("@quadra_lote", p_arrUpdate[4]));
objcmd.Parameters.Add(new SqlParameter("@telefone", p_arrUpdate[5]));
objcmd.Parameters.Add(new SqlParameter("@email", p_arrUpdate[6]));
objcmd.Parameters.Add(new SqlParameter("@cidade", p_arrUpdate[7]));
objcmd.Parameters.Add(new SqlParameter("@uf", p_arrUpdate[8]));
objcmd.Parameters.Add(new SqlParameter("@nome_pai", p_arrUpdate[9]));
objcmd.Parameters.Add(new SqlParameter("@nome_mae", p_arrUpdate[10]));
objcmd.Parameters.Add(new SqlParameter("@situacao", p_arrUpdate[11]));
objcmd.Parameters.Add(new SqlParameter("@atividade", p_arrUpdate[12]));
objcmd.ExecuteNonQuery();
return true;
}
catch (SqlException sqlerr)
{
throw sqlerr;
}
finally
{
this.desconectar();
}
else
{
return false;
}
}
modified 6-Sep-17 13:52pm.
|
|
|
|
|
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
|
|
|
|
|