Visual C# Dataset to Class - c#

I am a student programer working in Visual Studios C# and I am trying to access information from my dataset and insert the data into a class. This is not, by any means, homework I've just have some personal projects I've been wanting to try. I have tried several approaches that have been mentioned on this site; however, no information is displayed. My code looks similar to this:
class MyClass
{
public string ColumnData1
{
get; set;
}
public int ColumnData2
{
get; set;
}
public string Display()
{
string MyString = ColumnData1 + ColumnData2.ToString();
return MyString;
}
}
I use this to insert data into class:
private void MyForm_Load(object sender, EventArgs e)
{
MyDataSet.MyDataTable MDT = new MyDataSet.MyDataTable();
List<MyClass> MyList = new List<MyClass>();
foreach (DataRow MyDataRow in MDT.Rows)
{
Mylist.Add(new MyClass()
{
ColumnData1 = (string)MyDataRow["Data1"],
ColumnData2 = (int)MyDataRow["Data2"]
{
}
Lastly to display the information:
textBox1.Text = Mylist[0].Display();
}
In the end, however, nothing ends up displaying. This also wasn't the only thing I've tried to display the information.. it's like the information doesn't exist. I don't receive any errors and when I try to add a "Stop Point" at the insertion part of the code it just skips it. I should mention also that I have many text boxes and list boxes that pull data off the database just fine, of course Visual Studios binds those for me. Any help is very much appreciated.
Edit:
Ok, excluding the new data table. If I had an existing dataset how would I would I use it to fill my class.

That's normal because your DataTable is empty (Your create instance)
MyDataSet.MyDataTable MDT = new MyDataSet.MyDataTable();//<------Empty
foreach (DataRow MyDataRow in MDT.Rows)
{
....
}
Fill DataSet :
string queryString =
"SELECT .... FROM YourTable";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, "NameOfDataSet");

You must have some data in MDT before you insert it in the MyList, List of MyClass.
Declaration without data:
MyDataSet.MyDataTable MDT = new MyDataSet.MyDataTable();

Related

Add the contents of a DataGridView to an existing XML file

So I finally was able to create a XML and change it as I want but now I needed to add the contents of a DataGridView to it. I thought that's quite easy as I saw the options to place it into a DataSet and use XmlWrite, but that was a mistake of me. Note that I'm still trying to learn C# so probably I make a silly mistake here. It is still not working maybe someone is willing to point me out what I am doing wrong?
I actually have two issues with this:
It ForEach loop doesn't get the existing column names
It doesn't add the table and its contents to the XML file
private void CreateClientFile()
{
string filename;
filename = Company + "_" + SiteName + ".xml";
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("CompanyProfile");
doc.AppendChild(root);
//Save document on Harddisk
doc.Save(#"C:\Users\NLRAGIL\Documents\10 - VibroManager\" + filename);
//Need to save first and than load again????
//Load document into program
doc.Load(#"C:\Users\NLRAGIL\Documents\10 - VibroManager\" + filename);
XmlNode main = doc.SelectSingleNode("CompanyProfile");
//Create Company name element
XmlElement companyname = doc.CreateElement("CompanyName");
companyname.InnerText = CompanyName;
main.AppendChild(companyname);
//Create sitename element
XmlElement sitename = doc.CreateElement("Sitename");
sitename.InnerText = SiteName;
main.AppendChild(sitename);
//Create IMO element
XmlElement imo = doc.CreateElement("IMO");
imo.InnerText = IMO;
main.AppendChild(imo);
DataTable dt = new DataTable();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dt.Columns.Add("column" + i.ToString());
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
dr["column" + j.ToString()] = row.Cells[j].Value ;
}
dt.Rows.Add(dr);
}
//Create DataSet and add the datatable
DataSet ds = new DataSet();
ds.Tables.Add(dt);
//Give the file name for where to write to.
ds.WriteXml(#"C:\Users\NLRAGIL\Documents\10 - VibroManager\" + filename);
//Show example for debugging
doc.Save(#"C:\Users\NLRAGIL\Documents\10 - VibroManager\" + filename);
System.Console.WriteLine(doc.InnerXml);
}
EXTRA CLARIFICATION:
The form I have looks as below:
The Textbox in the groupbox "Client Information" I'm able to save in a XML file. By altering the value of the numeric control I can express how much machine the particular client has. And the DataGridView gets more or less rows. But the information from the DataGridView I'm unable to append to the created XML file.
So the information from "Machine Name", "Serial No" etc I can't add to the XML file.
This is what I wanted to do, so later on in the program I can add certain measurements of each machine to it and store also in the same file.
But whatever I do my XML file looks like this:
I hope I explained it better now sorry for the confusion
Your question is Add the contents of a DataGridView to an existing XML file and you say your first issue is that your ForNext loop is not giving you the column names and your second issue is that the code fails to serialize the record to an XML file on disk. These two goals can be simplified by using Data Binding. This decouples your data from the view, making it easier to process. I would like to give you some insight if you wanted to try it out using the CompanyProfile in your code.
First, a CompanyProfile class declares the intended public properties:
public class CompanyProfile
{
public string CompanyName { get; set; }
public string SiteName { get; set; }
public string IMO { get; set; } = "Some Value";
}
Next, in your MainForm class a BindingList<CompanyProfile> is declared and attached to the DataGridView like this:
BindingList<CompanyProfile> DataSource = new BindingList<CompanyProfile>();
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
if(!DesignMode)
{
// Attach the data source to the view. Now changes to source records refresh in the view.
dataGridView1.DataSource = this.DataSource;
// Adding one or more records will generate the columns.
DataSource.Add(new CompanyProfile { CompanyName = "Linear Technology", SiteName = "Colorado Design Center"});
DataSource.Add(new CompanyProfile { CompanyName = "Analog Devices", SiteName = "1-1-2"});
// Use string indexer to get a column
dataGridView1.Columns[nameof(CompanyProfile.CompanyName)].AutoSizeMode = dataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns[nameof(CompanyProfile.SiteName)].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
DataGridView1.AllowUserToAddRows = false;
}
}
The resulting DataGridView now looks like this:
This method makes a single file from a CompanyProfile record using XmlSerializer (but this is just one approach - and you could also serialize the entire list at one time if you choose).
private void CreateClientFile(CompanyProfile companyProfile, string fileName)
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(CompanyProfile));
using (var writer = new StreamWriter(fileName))
{
x.Serialize(writer, companyProfile);
}
// Open the file to view the result
Process.Start("notepad.exe", fileName);
}
Now, iterate a ForNext loop on the DataSource not the DataGridView. You no longer need to worry about columns because you have the bound properties instead.
private void btnSerialize_Click(object sender, EventArgs e)
{
var appData = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"datagridview_to_xml");
Directory.CreateDirectory(appData);
// Iterate the datasource list, not the DataGridView.
foreach (CompanyProfile companyProfile in DataSource)
{
CreateClientFile(
companyProfile,
fileName: Path.Combine(appData,
$"{companyProfile.CompanyName}_{companyProfile.SiteName}.xml")
);
}
}
Clicking the [Serialize] button reveals the two files.

SQLite with Dapper C# - Windows Form: Using ComboBox Lisl Properties to retrieve database data with a foreign key

I work with C# in Visual Studio 2019. My database is in SQLite using Dapper.
Here is what I am struggling with.
I have 2 tables in my database that are connected.
The parent, tbClient. And the child table, tbProject.
tbProject has a field to ClientId.
I use a ComboBox to WireUpp the Data from the database to my form. I have a form to Client, and a form for the Project, in this form I chose a CLient in a ComboBox, and save its ID in my tbProjet.
The idea is simple, but I am struggling because I am using an example that was made in Windows (WPF), and my application is in Windows Forms. I noticed that the Properties of the ComboBox are not the same, then I am having some trouble accessing the correct Project field when I want to open the Project of a specific Client.
Let´s show how it's done in the WPF app and in my WinForm app. I think is going to be more clear to get some help.
The codes of the Project Form are below: the first is the WPF app, and the second one is the WinForm where I was not able to make work yet.
WPF Application:
// WPF Application:
namespace MyApp.Controls
{
public ProjectControls()
{
InitializeComponent();
InitializeClientList();
WireUpDropDowns();
}
private void WireUpDropDowns()
{
clientDropDown.ItemsSource = clients;
clientDropDown.DisplayMemberPath = "Name";
clientDropDown.SelectedValuePath = "Id";
projectDropDown.ItemsSource = projects;
projectDropDown.DisplayMemberPath = "DisplayValue";
projectDropDown.SelectedValuePath = "Id";
}
private void InitializeClientList()
{
string sql = "select * from Client order by Name";
var clientList = SqliteDataAccess.LoadData<ClientModel>(sql, new Dictionary<string, object>());
clientList.ForEach(x => clients.Add(x));
}
private void clientDropDown_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LoadProjectDropDown();
}
private void LoadProjectDropDown()
{
string sql = "select * from tbProject where ClientId = #ClientId";
Dictionary<string, object> parameters = new Dictionary<string, object>
{
{ "#ClientId", clientDropDown.SelectedValue }
};
var records = SqliteDataAccess.LoadData<ProjectsModel>(sql, parameters);
projects.Clear();
records.ForEach(x => projects.Add(x));
}
}
Windows Form Application:
// Windows Forms Application:
namespace MyApp.Controls
{
public ProjectControls()
{
InitializeComponent();
InitializeClientList();
WireUpDropDowns();
}
private void WireUpDropDowns()
{
clientDropDown.DataSource = null;
clientDropDown.DataSource = clients;
clientDropDown.DisplayMember= "Name";
clientDropDown.ValueMember = "Id";
projectDropDown.DataSource = null;
projectDropDown.DataSource= projects;
projectDropDown.DisplayMember = "DisplayValue";
projectDropDown.ValueMember= "Id";
}
private void InitializeClientList()
{
string sql = "select * from Client order by Name";
var clientList = SqliteDataAccess.LoadData<ClientModel>(sql, new Dictionary<string, object>());
clientList.ForEach(x => clients.Add(x));
}
private void clientDropDown_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LoadProjectDropDown();
}
private void LoadProjectDropDown()
{
string sql = "select * from tbProject where ClientId = #ClientId";
Dictionary<string, object> parameters = new Dictionary<string, object>
{
{ "#ClientId", clientDropDown.SelectedValue }
// --> I think the problem is here, I am passing an object to the database where ClientId is an integer type. I tried to use SelectedIndex instead, but with this property, I do not get the correct Project from the table
};
var records = SqliteDataAccess.LoadData<ProjectsModel>(sql, parameters);
projects.Clear();
records.ForEach(x => projects.Add(x));
}
}
In the Windows Form Application I get this Error Message from my AccesDataBase Routine:
System.NotSupportedException: 'The member ClientId of type AppLibrary.Models.ClientModel cannot be used as a parameter value'
So I think the basic question here is Am I using the ComboBOx Properties correct? What I am missing?
Thank you in advance for any help received.
Verônica.
I found out about my mistake.
The property of the Combobox is correct.
I was passing the wrong parameter to the ClientDropDown.SelectedValue in other parts of the code that I haven´t shared here.
I was trying to select a specific client in the ClientDropDown through code but I was passing SelectedIndex to the SelectedValue.
I used the Breakpoints and was able to find the error, and now is working with this code that I share here in the question, it is correct.

How to get the recently added values from database to Autocomplete Textbox

How can i get the recently added values from my database to my textbox (with Autosuggest) I need to exit the application just to see the recently added values to my textbox. I hope someone would be able to help me in this matter.
public void AutoSuggest()
{
List<string> col = new List<string>();
using (var con = SQLConnection.GetConnection())
{
using (var select = new SqlCommand("Select Codeitem from employee_product", con))
{
using (var reader = select.ExecuteReader())
{
while (reader.Read())
{
col.Add(reader["Codeitem"].ToString());
}
txt_code.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txt_code.AutoCompleteSource = AutoCompleteSource.CustomSource;
txt_code.AutoCompleteCustomSource.Clear();
txt_code.AutoCompleteCustomSource.AddRange(col.ToArray());
AddingProduct();
}
}
}
}
This Image is for adding my product and you can see the recently added product the selected one.
This image is for getting the code value of my product. You can see when i tried to input the code, he can't suggest the recently added

How can I get rid of double \ character (\\) which I keep in database

I have some data in my MsSql database and send them to my Android app by Csharp Web Apis. There some unicode characters in nvarchar fields. There are in the middle of the string data. For example: 'F\u2081 is greater than F\u2082'
The data keeps going to the mobile app as "F\u2081 is greater than F\u2082" . So the unicode characters are never displayed successfully.
I searched and tried many methods but no success so far.
You can test and see the result of the web api (post)
http://www.kelimex.com.tr/teogapi/api/Fen
In the result view, "message" field data comes from the database.
But the "explanation" field data is entered by me in the source code of web api.
As you will see the is no problem in the field "explanation". But "message" field keeps showing up incorrectly.
Does anyone have any experience on this issue?
Here is the csharp code which pulls the data from Sql and returns a list for the web api. Currently there is no encoding-decoding-etc... None of them worked anyway.
public List<Result> test()
{
List<Result> list = new List<Result>();
if (ConnectToDB())
{
try
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("__tm_test", conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(ds, "ds");
if (ds.Tables.Count > 0)
{
Result item = new Result();
item.statusCode = 1;
item.status = true;
item.message = ds.Tables[0].Rows[0]["FieldNVarchar"].ToString();
item.explanation = "F\u2081 is greater than F\u2082";
list.Add(item);
}
ds.Dispose();
da.Dispose();
}
catch (Exception e)
{
}
}
return list;
}
You should use HttpUtility.UrlEncodeUnicode and HttpUtility.UrlEncode for text you are setting a variable. Please check the below example:
//Encode a text
var myText = HttpUtility.UrlEncodeUnicode(MyText)
//And Decode text you are getting
var MyTextNew = HttpUtility.UrlEncode(text)

public dataset in C#

i need to be able to save and retrieve data in a dataset in multiple places. i didnt want to copy and paste all my code since its pretty large, and i hope my super short version gets the idea across. thanks in advance. i currently have something along the lines of...
class program
{
DataSet ds;
static void main(...)
{
getMe(string);
}
public void getMe(string x)
{
ds = new mydataset();
DataRow dr = new ds.Tables[0].NewRow();
//blah blah add x to dr[ column ]
ds.Tables[0].Rows.Add(dr.ItemArray);
}
public void readMe()
{
**need to read dataset here with info added in rows from getMe()
}
}
EDIT:
edited DataSet = ds; to DataSet ds; to reflect my actual code.
if i call getMe(string) in my main, it errors with..."an object reference is required for a non-static field, method or property."
if i change getMe(string x) to public static void getMe(string) the error goes away but shows again for
ds = new mydataset();

Categories

Resources