|
Member 14103987 wrote: but I seem to do something wrong.
It would help if you explained why it is 'wrong'. Is there an error? Or does the data just not show up.
Your code is attempting to insert one value into a table one row at a time. That will only work if the table only has one column. You can insert just one value, depending on how the table is created, but in that case your 'Insert' must define that column. The form would look like the following
Insert into MyTable (MyRow1) values(1)
And your code does not have the '(MyRow1)' part.
Second possibility is that because you say 'ToString()' that means the type of num1 is a String. Exactly as you requested.
But because you named it 'num1' it seems likely that you actually want a number. And very possible that AddWithValue() is then translating that to a string value for the database. So if your 'MyRow1' is a database type of 'int' but your code is creating the following, because 'num1' is a string, it will not work. (Notice the ticks around the number.)
Insert into MyTable values('1')
|
|
|
|
|
Thanks for the suggestions. Here is an update that would explain everything in more detail.
I have a datatable with values, the first column will always be a string and the rest (5 columns) will have numbers. I have used the code that I shared to make it work for a datagridview but now I want to make it work for a datatable . The way I though was best was to take each row into the postgresql server and store it until its needed later. It seems like a sqladapter seems to be a better way to handle this and therefore I had some help trying to figure this out with the following code:
using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter("SELECT num1, num2, num3, num4, num5, num6 FROM " + Table + ";", Conn))
{
NpgsqlCommand insert = new NpgsqlCommand("INSERT INTO " + Table + " VALUES (@num1, @num2, @num3, @num4, @num5, @num6);", Conn);
insert.Parameters.Add("@num1", NpgsqlDbType.Text, 200, "1");
insert.Parameters.Add("@num2", NpgsqlDbType.Text, 50, "2");
insert.Parameters.Add("@num3", NpgsqlDbType.Text, 50, "3");
insert.Parameters.Add("@num4", NpgsqlDbType.Text, 50, "4");
insert.Parameters.Add("@num5", NpgsqlDbType.Text, 50, "5");
insert.Parameters.Add("@num6", NpgsqlDbType.Text, 50, "6");
adapter.InsertCommand = insert;
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
DataTable table = new DataTable();
adapter.FillSchema(table, SchemaType.Source);
DataRow row = table.NewRow();
row["1"] = row.Table.Rows[0][0].ToString();
row["2"] = row.Table.Rows[0][1].ToString();
row["3"] = row.Table.Rows[0][2].ToString();
row["4"] = row.Table.Rows[0][3].ToString();
row["5"] = row.Table.Rows[0][4].ToString();
row["6"] = row.Table.Rows[0][5].ToString();
table.Rows.Add(row);
adapter.Update(table);
}
}
The code seems to work until the actual strings/values need to be put inside the SQL server table(see inside of code to know where the code breaks out). If anyone knows how to make the code work or is willing to show whats missing I would gladly appreciate it.
|
|
|
|
|
If the last 5 columns are numbers, why is your parameter code treating them all as strings?
|
|
|
|
|
Providing the details of the exception would have helped!
Member 14103987 wrote:
DataTable table = new DataTable(); That creates a new empty DataTable , with no rows.
Member 14103987 wrote:
adapter.FillSchema(table, SchemaType.Source); That configures the columns of the table. There are still no rows in the table.
Member 14103987 wrote:
DataRow row = table.NewRow(); That creates a new row with the same schema as the table. There are still no rows in the table.
Member 14103987 wrote:
row.Table.Rows[0][0] This attempts to retrieve the value of the first column of the first row of a table with no rows.
Unsurprisingly, this throws an IndexOutOfRangeException with the message "There is no row at position 0."
You cannot copy data that doesn't exist from an empty DataTable to itself. You need to work out precisely where the source data is stored, and copy from that instead.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hello, Profs
Please, I need help in my c# journal code as I find it difficult to get rid of the errors.
Below is the sample of my c# code and I will appreciate if the errors could be fixed.
Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Journal
{
class Program
{
static void Main(string[] args)
{
Journal journal = new Journal();
while (true)
{
Console.WriteLine("1. Write a new entry");
Console.WriteLine("2. Display journal");
Console.WriteLine("3. Save journal");
Console.WriteLine("4. Load journal");
Console.WriteLine("5. Quit");
Console.Write("Enter your choice: ");
int userChoice = Convert.ToInt32(Console.ReadLine());
if (userChoice == 1)
{
string chosenPrompt = journal.GetRandomPrompt();
Console.WriteLine("Prompt: " + chosenPrompt);
Console.WriteLine("Write your response:");
string response = Console.ReadLine();
Entry newEntry = new Entry
{
Date = DateTime.Now,
Prompt = chosenPrompt,
Response = response
};
journal.AddEntry(newEntry);
}
else if (userChoice == 2)
{
journal.DisplayEntries();
}
else if (userChoice == 3)
{
Console.WriteLine("Enter a filename to save journal:");
string filename = Console.ReadLine();
journal.SaveJournal(filename);
}
else if (userChoice == 4)
{
Console.WriteLine("Enter a filename to load journal:");
string filename = Console.ReadLine();
journal.LoadJournal(filename);
}
else if (userChoice == 5)
{
break;
}
else
{
Console.WriteLine("Invalid choice. Try again.");
}
}
}
}
class Entry
{
public DateTime Date { get; set; }
public string Prompt { get; set; }
public string Response { get; set; }
}
class Journal
{
private List<string> prompts = new List<string>
{
"What did you learn today?",
"What are you grateful for?",
"What did you accomplish today?",
"What challenges did you face today?",
"What are your goals for tomorrow?"
};
private List<Entry> entries = new List<Entry>();
public string GetRandomPrompt()
{
Random rand = new Random();
int index = rand.Next(prompts.Count);
return prompts[index];
}
public void AddEntry(Entry entry)
{
entries.Add(entry);
}
public void DisplayEntries()
{
Console.WriteLine("Journal Entries:");
foreach (Entry entry in entries)
{
Console.WriteLine("Date: " + entry.Date);
Console.WriteLine("Prompt: " + entry.Prompt);
Console.WriteLine("Response: " + entry.Response);
Console.WriteLine("----------------");
}
}
public void SaveJournal(string filename)
{
using (Stream stream = File.Open(filename, FileMode.Create))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, entries);
}
}
public void LoadJournal(string filename)
{
if (File.Exists(filename))
{
using (Stream stream = File.Open(filename, FileMode.Open))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
entries = (List<Entry>)binaryFormatter.Deserialize(stream);
}
}
else
{
Console.WriteLine("File does not exist.");
}
}
}
}
|
|
|
|
|
Just dumping 137 lines of unexplained code and demanding that we "fix the errors" is unacceptable.
If you can't be bothered to explain precisely what the errors are, what you have tried, and where you are stuck, then you're not getting any help.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Oh! My bad. I am so sorry about that. Maybe it's because I am a baby programmer; that's why I did what is unacceptable. Please pardon my manners.
I am working on a c# journal app, and in the process I came across a number of errors, which I have tried my best to fix but to no avail. The errors are just too numerous to mention, and that's why I couldn't mention any of them during my first posting.
However, the following are the errors I came across in my code:
In line 76 (class journal) - Invalid expression term '}' [C:\Users\USER\De(CS1525)
In line 79 and 83 - Invalid token '{' in class, record, struct, or(CS1519)
In line 80 - Tuple must contain at least two elements. [C:(CS8124) and Invalid token ')' in class, record, struct, o(CS1519)
In line 84 - Invalid token '(' in class, record, struct, o(CS1519) and Type expected [C:\Users\USER\Desktop\cse210\c(CS1031)
In line 87 and 102 - Type or namespace definition, or end-of-file e(CS1022)
In line 89 - Top-level statements must precede namespace an(CS8803)
In line 117 and 128 - 'BinaryFormatter.Serialize(Stream, object)' is obsolete: 'BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.' [Develop02]csharp(SYSLIB0011)
Thank you.
|
|
|
|
|
Most of those errors don't relate to the code you've posted.
The only error generated by your code is the one that OG posted below - and I'm not convinced that that's a genuine error, and not just a requirement of the online compiler used.
After making the Program class and Main method public , your code compiles without any of those errors:
Journal | C# Online Compiler | .NET Fiddle[^]
(The "BinaryFormatter serialization is obsolete..." message is a warning, and won't prevent your code from running. Read the provided link[^] if you want to get rid of it.)
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
It built without errors for me, even without @OriginalGriff's suggested corrections. And it ran OK up until the point where it tried to save the journal entries.
|
|
|
|
|
Thank you so much, Richard.
Your explanation is quite appreciated, and I will never take it for granted. I am sure that I am more confident in getting rid of the errors with your explanation and with the aid of the compiler that you just shared with me.
Gracias!
|
|
|
|
|
I just tried building your code and did not get any errors. Which compiler and framework are you using?
|
|
|
|
|
Errors get in the way gradually, as you code. I think it’s better to describe what you did when you started to get the error messages you posted.
Code of that complexity doesn’t fall from the sky. Try to explain with your own words what you are doing and how did you got to have so much source code.
|
|
|
|
|
Read the error messages carefully - they are there to help you!
Public Main() method is required in a public class
Your class isn't public and your Main method isn't public
So change that:
public class Program
{
public static void Main(string[] args)
{
How hard was that to work out?
You should expect to get syntax errors every day, probably many times a day while you are coding - we all do regardless of how much experience we have! Sometimes, we misspell a variable, or a keyword; sometimes we forget to close a string or a code block. Sometimes the cat walks over your keyboard and types something really weird. Sometimes we just forget how many parameters a method call needs.
We all make mistakes.
And because we all do it, we all have to fix syntax errors - and it's a lot quicker to learn how and fix them yourself than to wait for someone else to fix them for you! So invest a little time in learning how to read error messages, and how to interpret your code as written in the light of what the compiler is telling you is wrong - it really is trying to be helpful!
So read this: How to Write Code to Solve a Problem, A Beginner's Guide Part 2: Syntax Errors[^] - it should help you next time you get a compilation error!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
OMG! I am grateful for your explanation, and may you continue to grow in knowledge, wisdom, and understanding.
Thank you so much for your kind words, and I promise to take my time to read and understand the beginner's guide that you shared with me. It's as if you know that I am a baby programmer. Lol
Gracias!
|
|
|
|
|
You're welcome!
We all have to start somewhere.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
If I can offer one further word of advice - in my opinion, the most important part of @OriginalGriff's article is the line Quote: Fixing one syntax error can get rid of a whole load of other ones so always start with the first, not the last! Embed that advice in your head and don't let it leave! It could save you many hours of frustration
|
|
|
|
|
Still don't know why this happens but it doesn't matter. I found that setting my control
to DoubleBuffered = true, the display time goes to 0.
Sorry for the post.
Can some tell me why displaying the transparent pixel takes so much time?
See bottom of sample for time comparison.
public class CellColor
{
public Rectangle Rect;
public Color Color;
public CellColor(Rectangle rect, Color clr)
{
Rect = rect;
Color = clr;
}
}
// At form load time, this array is loaded with pixel data from a 32 x 32 Icon.
// About half of the pixels in the sample icon are transparent (A=0,R=255,G=255,B=255).
private CellColor[,]? _CellBounds;
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawCells(e.Graphics);
}
private void DrawCells(Graphics gr)
{
int iWd = this._CellBounds!.GetUpperBound(0) + 1;
int iHt = this._CellBounds.GetUpperBound(1) + 1;
Stopwatch sw = new();
sw.Start();
for (int iRow = 0; iRow < iHt; iRow++)
{
for (int iCol = 0; iCol < iWd; iCol++)
{
CellColor cc = this._CellBounds[iRow, iCol];
using(SolidBrush br = new(cc.Color))
{
gr.FillRectangle(br, cc.Rect);
}
}
}
sw.Stop();
// Displaying the data without pixel modification takes about 60 milliseconds.
// When loading _CellBounds, if I replace the transparent pixel with a real color like Color.White,
// this loop takes 4 milliseconds.
DebugClass.WriteLine(string.Format("{0}", sw.ElapsedMilliseconds));
}
-- modified 29-Jan-23 8:08am.
|
|
|
|
|
I did not try running the code, but my thought is:
When you use a solid color, the updated values can be written straight to memory without any checks.
Once you alpha blend then each pixel will have to be merged with whatever is in the current image. So each pixel goes from a single write to read, calculate, then write.
Sure they could have optimized even further and simply not do anything if the alpha channel is 0, but apparently they did not. But you can do this easily yourself -one you have the CellColor you can check if it has a 0 alpha channel and skip setting up the brush and drawing when this is the case.
|
|
|
|
|
I'm programming using WinForms in C# .NET 2.0 and sometimes I want to disable the entire GUI so that the user can't e.g. press any buttons or change any comboboxes. I found this through googling Disable form Controls Without Being Gray!!![^] and I thought it was working great, until today. Whenever USB-cables are connected/disconnected on my PC, I get an event and then I disable the GUI, using the code I linked to above, and re-enumerate my virtual COM-ports and then I enable the GUI again. I discovered that executing this.Controls.Add(alphapanel); takes almost 2 seconds and executing alphapanel.BringToFront(); takes another second! Is there anything I can do to speed this up?
|
|
|
|
|
You should monitor the individual connections so you don't have to drop and reconnect "everything". You wouldn't drop things in a mission critical app and you should treat all apps as if they were (IMO).
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
I don't disconnect anything, I just ask the Device Manager what Com ports are present and then I compare that with what was present before and take appropriate actions (e.g. remove or add Com port from a combobox). But this is not what's taking so long, it's the AlphaPanel handling that takes time.
|
|
|
|
|
If the GUI is slow, it means you should be doing this "AlphaPanel handling" in the background.
BackgroundWorker Class (System.ComponentModel) | Microsoft Learn
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
After a test with loaded (I loaded them from a hdd-drive) 3000x3000 images (Same Datatype) it worked fast and without problems. Too much changes
|
|
|
|
|
{
Can anyone help with c# source code or directive on how to achieve the subject?
}
|
|
|
|
|
While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you.
So we need you to do the work, and we will help you when you get stuck. That doesn't mean we will give you a step by step solution you can hand in!
Start by explaining where you are at the moment, and what the next step in the process is. Then tell us what you have tried to get that next step working, and what happened when you did.
If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|