|
You're missing a comma between the last two columns:
SELECT p.pcode, p.pdesc, b.brand, c.category, p.price p.qty should be:
SELECT p.pcode, p.pdesc, b.brand, c.category, p.price, p.qty
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Im trying to make loadData to datagridview in c#. Is there something wrong on my code?
public void LoadRec()
{
try
{
int i = 0;
dgvProduct.Rows.Clear();
_sqlConn.Open();
_sqlCmd = new SqlCommand("SELECT p.pcode, p.pdesc, b.brand, c.category, p.price, p.qty FROM tblProduct as p inner join tblBrand as b on b.id = p.bid inner join tblCategory as c on c.id = p.cid where p.pdesc like '" + txtSearchProd.Text + "%'", _sqlConn);
_sqlDR = _sqlCmd.ExecuteReader();
while (_sqlDR.Read())
{
i++;
dgvProduct.Rows.Add(i, _sqlDR[0].ToString(), _sqlDR[1].ToString(), _sqlDR[2].ToString(), _sqlDR[3].ToString(), _sqlDR[4].ToString(), _sqlDR[5].ToString());
}
_sqlDR.Close();
_sqlConn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
_sqlConn.Close();
}
|
|
|
|
|
Yes. Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
Also, don't store connection, command, or data reader objects in class-level fields. Create them as local variables when they're required, and wrap them in using blocks.
using (var sqlConn = new SqlConnection("..."))
using (var sqlCmd = new SqlCommand("SELECT p.pcode, p.pdesc, b.brand, c.category, p.price, p.qty FROM tblProduct as p inner join tblBrand as b on b.id = p.bid inner join tblCategory as c on c.id = p.cid where p.pdesc like @SearchProd + '%'", sqlConn))
{
sqlCmd.Parameters.AddWithValue("@SearchProd", txtSearchProd.Text);
sqlConn.Open();
using (var sqlDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (sqlDR.Read())
{
i++;
dgvProduct.Rows.Add(i, sqlDR[0].ToString(), sqlDR[1].ToString(), sqlDR[2].ToString(), sqlDR[3].ToString(), sqlDR[4].ToString(), sqlDR[5].ToString());
}
}
}
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
When I try to execute the code Sir, there is no data displayed on my datagrid.
I also try the to run these query on my sqlserver.
SELECT p.pcode, p.pdesc, b.brand, c.category, p.price, p.qty
FROM tblProduct
as p inner join tblBrand
as b on b.id = p.bid inner join tblCategory
as c on c.id = p.cid
where p.pdesc like '%'
but theres no data showed.
|
|
|
|
|
Then there is no matching data in your database.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Start by cutting it down and trying it in SSMS:
SELECT p.pcode, p.pdesc, b.brand, c.category, p.price, p.qty
FROM tblProduct p
INNER JOIN tblBrand b
ON b.id = p.bid
WHERE p.pdesc LIKE '%'
And see if you get any rows.
If you don't, remove the JOIN and see what p.pid values you do get, then look at tblBrand to see if they exist. Remember that an INNER JOIN requires a matching entry in BOTH tables to return ANY rows.
If you do, add the second JOIN and see what you get.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I have two classes like this
public myclass1
{
public int Id {set;get;)
public myclass2 MyClass2{set;get;)
}
public myclass2
{
public int Id {set;get;}
public string Name {set;get;}
}
public list<myclass1> mylist = new List<myclass1>() ;
my list has been bonded to datagridview .
when displying the collection in the grid , the myclass1 is displaying the object name "DomaninName.myclass2"
how to display the propery "Name" of myclass2
|
|
|
|
|
you can overwrite the ToString function
|
|
|
|
|
thank you it works fine for me .
|
|
|
|
|
First, fix the compilation errors in your code: use of ')" where it should be '}', missing class keyword on class definitions, missing uppercase on List , that sort of thing.
So us code that works to demonstrate your problem - not a lump of crap your threw together and didn't check at all ...
You can display what you want as the cell content, just override ToStrign in your class:
public class myclass2
{
public int Id { set; get; }
public string Name { set; get; }
public override string ToString()
{
return $"{Id}:{Name}";
}
}
You can also set the column header text to something more human readable than the property name - just set the HeaderText property of the column:
myDataGridView.DataSource = mylist;
myDataGridView.Columns[1].HeaderText = "My other class";
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I have two c# form apps which use openFileDialog. One displays the targa bitmap with the system thumbnail in the corner (app1) and the other displays the system thumbnail(app2). The one which fails to display the targa bitmap shows the option to create a new folder while the other does not offer that option.
App1 I created using Microsoft tutorial1 Create a picture Viewer
App2 is called TargaImage_demo downloaded from this site.
I have compared the two projects making sure they use the same .Net framework but I cannot see why one works as I want it to do while the other fails to display the bitmaps.
Does anyone know why there is a difference between the two openFileDialogs?
|
|
|
|
|
Don't post this here - if you got the code from an article, then there is a "Add a Comment or Question" button at the bottom of that article, which causes an email to be sent to the author. They are then alerted that you wish to speak to them.
Posting this here relies on them "dropping by" and realising it is for them.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
At a guess, have you called EnableVisualStyles[^] in one application but not the other?
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
OpenFileDialog has nothing to do with displaying the image at all.
An OFD is only concerned with one thing, returning a string containing the path to a file. That's it. Nothing else.
The code to display the image is somewhere else and is where the problem appears to be.
|
|
|
|
|
Hi all,
I have a project which is divided to two parts:
1/ The first one is TCP handling message from a pertinant connection(so connection should be always connected till user disconnect it).
2/ The second part is another application which process the messages recieved.
So please for the first on how can handle message from a connection already established and send it internaly to the second project and after that reply.
|
|
|
|
|
What have you tried?
Where are you stuck?
What help do you need?
THis is a broad subject with no real detail provided, and we can't just tell you what to do, because we have no idea what stage you are at already. Heck, we don't even know if the "second application" is a separate process from the first - and that's unbelievably relevant!
So answer the three questions above, and remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Dear all,
I have two applications:
Console one it server for Tcp pertinant socket :
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.IO;
namespace Asychn_Server
{
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
allDone.Reset();
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
content = state.sb.ToString();
log("Socket status : " + handler.Connected);
log("From socket : " + content);
Send(handler, content);
log("Socket status : " + handler.Connected);
}
}
private static void Send(Socket handler, String data)
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
log("TO socket : " + bytesSent + " -As reply");
log("Socket status send: " + handler.Connected);
allDone.Set();
log("Socket status send2: " + handler.Connected);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
public static void log(string strLog)
{
StreamWriter log;
FileStream fileStream = null;
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo;
string logFilePath = "C:\\Logs\\";
logFilePath = logFilePath + "LogServer-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
if (!logFileInfo.Exists)
{
fileStream = logFileInfo.Create();
}
else
{
fileStream = new FileStream(logFilePath, FileMode.Append);
}
log = new StreamWriter(fileStream);
log.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + ": " + strLog);
log.Close();
}
}
}
And client one as Desktop Application:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace Asynch_client_form_2
{
public partial class Form1 : Form
{
private const int port = 11000;
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
private static String response = String.Empty;
private static Socket client;
private void ConnectBtn_Click(object sender, EventArgs e)
{
try
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
}
catch (Exception ex)
{
ExceptionTextBox.Text = ex.Message;
}
}
private void SendBtn_Click(object sender, EventArgs e)
{
try
{
Send(client, "MY message");
sendDone.WaitOne();
Receive(client);
MsgTextBox.Text = response;
}
catch (Exception ex)
{
ExceptionTextBox.Text = ex.Message;
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void DisConnectBtn_Click(object sender, EventArgs e)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public Form1()
{
InitializeComponent();
}
private static void Receive(Socket client)
{
try
{
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
log(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
log("Reply : " + response);
}
receiveDone.Set();
}
}
catch (Exception e)
{
log(e.ToString());
}
}
private static void Send(Socket client, String data)
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int bytesSent = client.EndSend(ar);
sendDone.Set();
}
catch (Exception e)
{
log (e.ToString());
}
}
public static void log(string strLog)
{
StreamWriter log;
FileStream fileStream = null;
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo;
string logFilePath = "C:\\Logs\\";
logFilePath = logFilePath + "LogClient-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
if (!logFileInfo.Exists)
{
fileStream = logFileInfo.Create();
}
else
{
fileStream = new FileStream(logFilePath, FileMode.Append);
}
log = new StreamWriter(fileStream);
log.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + ": " + strLog);
log.Close();
}
}
}
In Client i need to press connect in order to estabish socket
and after that press send bouton to send messages without disconnecting socket.
with this code i couldn't handle reply for my message from server.
Can someone help me please
|
|
|
|
|
I swear I have been searching for an answer for hours but could not find any understandable example or article How do I make a property of a Winform usercontrol retain it's design time value? I added a new UserControl object. I put a label on the control. Added a property called "KeyText". I saw in few articles the attribute "DesignerSerailizationVisibility" mentioned so I added it as well.
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public string KeyText
{
get { return label1.Text; }
set
{
label1.Text = value;
}
} In the control, the default value of label1.Text is "X".
Then I added the control to a form. The property "KeyText" showed as one of the properties of the control. Great. So I changed it to "A". The design-time form showed A". Great. I compiled and ran the program - the control on the form showed "X" instead of "A".
What do I need to change to make the property persisteable? In VB6 I use something called PropBag to save and read design time properties.
|
|
|
|
|
OK, I added a new UserControl (called MyControl) to my project, dropped a label on it called MyLabel.
I changed it's Text property to "Default".
I added a string property called LabelText to the control:
public string LabelText
{
get
{
return MyLabel.Text;
}
set
{
MyLabel.Text = value;
}
}
And compiled the app.
Then I dropped two instances of MyControl (MC1 and MC2) onto my form.
I changed the LabelText property of MC2 to "Revised" in the designer and ran the app.
MC1 had "Default", MC2 had "Revised"
So what did I do that you didn't?
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
modified 14-Apr-20 2:40am.
|
|
|
|
|
Crazy Joe Devola wrote: [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
That line is the problem. The documentation isn't particularly clear, but:
With the DesignerSerializationVisibilityAttribute , you can indicate whether the value for a property is Visible , and should be persisted in initialization code, Hidden, and should not be persisted in initialization code, or consists of Content , which should have initialization code generated for each public, not hidden property of the object assigned to the property.
The property value is a String . The String type doesn't have any public properties which can be set, so no initialization code will be generated.
Either set it to DesignerSerializationVisibility.Visible , or remove the attribute.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
thank you. It is working now.
|
|
|
|
|
When i give print on first time it works , but when we click again it over printing
my print document code below
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.HasMorePages = false;
gf = e.Graphics;
lsx = 10;
lex = 797;
Brush brblack = new SolidBrush(Color.Black);
Pen p1 = new Pen(brblack);
int lpx = 10;
if (pgcount < 2)
{
dgline = 370;
dgtxt = 390;
dgdc = 350;
lsy1 = 345;
e.Graphics.DrawImage(img, -10, 0);
e.Graphics.DrawImage(img1, -10, 1000);
e.Graphics.DrawString(txtdate.Text, new Font("Times New Roman", 12, FontStyle.Bold), Brushes.Green, 600, 135);
e.Graphics.DrawString("Ref :" + txtqtnno.Text, new Font("Times New Roman", 12, FontStyle.Bold), Brushes.Black, 600, 155);
e.Graphics.DrawString("M/S " + txtclientname.Text, new Font("Times New Roman", 12, FontStyle.Regular), Brushes.Black, lpx, 170);
e.Graphics.DrawString(companyadd1, new Font("Times New Roman", 12, FontStyle.Regular), Brushes.Black, lpx, 195);
e.Graphics.DrawString(companyadd2, new Font("Times New Roman", 12, FontStyle.Regular), Brushes.Black, lpx, 220);
e.Graphics.DrawString("Kind Attn: " + cusname + "\nMob: " + cusno + ", E-mail: " + cusemail, new Font("Times New Roman", 12, FontStyle.Regular), Brushes.Black, lpx, 245);
e.Graphics.DrawString("Dear Sir,", new Font("Times New Roman", 12, FontStyle.Regular), Brushes.Green, lpx, 295);
e.Graphics.DrawString("sub : " + qtnsubject, new Font("Times New Roman", 12, FontStyle.Regular), Brushes.Green, lpx, 320);
}
else
{
lsy1 = 135;
dgline = 155;
dgtxt = 175;
dgdc = 137;
}
e.Graphics.DrawLine(p1, new Point(lsx, lsy1), new Point(lex, lsy1));
e.Graphics.DrawString(" Sr. no\t\t Descrption\t\t\tPrice\t Qty\t Amount", new Font("Times New Roman", 12, FontStyle.Bold), Brushes.Green, lpx, dgdc);
e.Graphics.DrawLine(p1, new Point(lsx, dgline), new Point(lex, dgline));
for (;drc<dataGridView2.RowCount - 1; drc++)
{
SizeF sf = gf.MeasureString(dataGridView2.Rows[drc].Cells[1].Value.ToString(), new Font(new FontFamily("Times New Roman"), 12F), 200);
rowspace = Convert.ToInt32(sf.Height);
dgtxt = dgtxt + 10;
chkpghgt = ((rowspace + dgtxt)*1);
if (chkpghgt > 1000)
{
e.HasMorePages = true;
pgcount++;
break;
}
gf.DrawString((drc+1).ToString(), new Font(new FontFamily("Times New Roman"), 12F), Brushes.Black, new RectangleF(new Point(50, dgtxt), sf), StringFormat.GenericTypographic);
gf.DrawString(dataGridView2.Rows[drc].Cells[1].Value.ToString(), new Font(new FontFamily("Times New Roman"), 12F), Brushes.Black, new RectangleF(new Point(120, dgtxt), sf), StringFormat.GenericTypographic);
gf.DrawString(dataGridView2.Rows[drc].Cells[3].Value.ToString(), new Font(new FontFamily("Times New Roman"), 12F), Brushes.Black, new RectangleF(new Point(405, dgtxt), sf), StringFormat.GenericTypographic);
gf.DrawString(dataGridView2.Rows[drc].Cells[4].Value.ToString(), new Font(new FontFamily("Times New Roman"), 12F), Brushes.Black, new RectangleF(new Point(550, dgtxt), sf), StringFormat.GenericTypographic);
gf.DrawString(dataGridView2.Rows[drc].Cells[5].Value.ToString(), new Font(new FontFamily("Times New Roman"), 12F), Brushes.Black, new RectangleF(new Point(690, dgtxt), sf), StringFormat.GenericTypographic);
dgline = dgtxt + rowspace + 10;
e.Graphics.DrawLine(p1, new Point(lsx, dgline), new Point(lex, dgline));
dgtxt = dgline;
}
e.Graphics.DrawLine(p1, new Point(lsx, lsy1), new Point(lsx, dgline));
e.Graphics.DrawLine(p1, new Point(lsx+80, lsy1), new Point(lsx+80, dgline));
e.Graphics.DrawLine(p1, new Point(370, lsy1), new Point(370, dgline));
e.Graphics.DrawLine(p1, new Point(485, lsy1), new Point(485, dgline));
e.Graphics.DrawLine(p1, new Point(625, lsy1), new Point(625, dgline));
e.Graphics.DrawLine(p1, new Point(lex, lsy1), new Point(lex, dgline));
}
|
|
|
|
|
You have an awful lot of objects there that should be disposed of. GDI resources are finite so every time you hit the event handler you are consuming resources without freeing them up. For instance, when you instantiate a Font, that's disposable so you should Dispose it.
|
|
|
|
|
At few places I am reading that multi threading is a process in which we run multiple threads under a process. But at few places I can see that multi threading is a process of executing multiple threads. Like Working on word and listening music from different application. As they both are having different process like word.exe and vlc.exe.
So what should be correct way so say about multi threading?
|
|
|
|
|
Multi-threading in the context of writing an app is the system of splitting work into multiple threads within a single process (the app execution space) to either free one thread (normally the GUI thread) of work, or to process data in parallel for higher throughput.
In this context, there is one process, which consists of memory plus a number of threads (which may change at run time)
The "working on word and listening to music" isn't really multi-threading - it's multi-process as the threads do not share a common execution space, and cannot access each other's memory. It's closer to the concept of "multitasking*" than "multi-threading", although it does involve separate threads as each process must have at least one active thread in order to remain in existence.
* Multitasking in the sense that "women are supposed to be better at it than men" but actually there isn't a difference
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|