|
Sorry to not respond earlier, but your solution works perfectly.
Thanks all for your help!
|
|
|
|
|
Hi all,
If you know all the ComboBoxes are inside the panel, why not just iterate of the Panel's ComboBox controls?
foreach (ComboBox cBox in panel1.Controls)
{
cBox.SelectedIndexChanged += cBox_SelectedIndexChanged;
}
Then when any of the ComboBox's SelectedIndexChanged events fire, you capture which one it is and do what needs to be done. eg.
void cBox_SelectedIndexChanged(object sender, EventArgs e)
{
var currentComboBox = sender as ComboBox;
if (currentComboBox == null)
return;
MessageBox.Show(currentComboBox.SelectedItem.ToString());
}
Neill
|
|
|
|
|
You could also consider using anonymous functions and lambda expressions if the function that is dynamically creating the combo box is also aware of what the drop down needs to do when updated.
public void AddComboBox(ComboBox cBox, Action<int> callback)
{
cBox.SelectedIndexChanged += (s,e) => { callback(cBox.SelectedIndex); };
}
|
|
|
|
|
The downside of this approach is that you've created a non-disposable event handler with that syntax.
|
|
|
|
|
Yes, you are correct that it would leak resources. If this were a long running application than that would be a problem otherwise the flexibility gained can potentially outweight a few kb of in memory comboboxes not reclaimed by the garbage collector. Another approach would to have an IDisposable class derive from combobox and reclaim the handler in Dispose() when the dynamically created boxes are deleted from their container.
|
|
|
|
|
public void GetBackup(string strDBName)
{
if (string.IsNullOrEmpty(strDBName))
{
MessageBox.Show("Server Name & Database can not be Blank");
return;
}
else
{
string destinationPath = ConfigurationManager.AppSettings.Get("BackupDestinationPath");
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
ServerConnection connection = new ServerConnection(ConfigurationManager.ConnectionStrings["CostAllocationEntities2"].ConnectionString);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[strDBName];
The above line Database db = sqlServer.Databases[strDBName]; is causing the below mentioned error.
Error : "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not> found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.(provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"}
Message : Failed to connect to server D>ata
Source=PC210090\\SQLEXPRESS;Initial Catalog=testdb2;Persist Secur>ity
Info=True;User ID=sa;password=password-1"}
|
|
|
|
|
The error message is pretty explicit, and even tells you what to do.
The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
So look at your connection string, and make sure that it is correct, and that the computer you are running your application on can "see" the "PC210090" PC on it's local network segment. Then check the user name and password combination is also correct.
And don't use the SA user login - it has complete access to the databases, you should be using a user with specific permissions at all times.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Yeah, the error is pretty self explanatory,a nd OriginalGriff is right, don't use sa account.
That being said; Did posting the code mess up your connection string or is that whats wrong? Also why are there 2 \'s between hostname and instance name?
Message: Failed to connect to server D>ata
Source=PC210090\\SQLEXPRESS;Initial Catalog=testdb2;Persist Secur>ity
Info=True;User ID=sa;password=password-1
Neill
|
|
|
|
|
My Connection string :
<add name="CostAllocationEntities2" connectionString="Data Source=PC210090\SQLEXPRESS;Initial Catalog=testdb2;Persist Security Info=True;User ID=sa;password=password-1" providerName="System.Data.SqlClient"/>
|
|
|
|
|
Well the connection string format looks fine.
There could still be quite a few things causing the problem.
1. Are your sure the PC210090 name is correct?
2. Is SQLEXPRESS correct or are you using a named instance?
3. Is the DB name correct?
4. Is the username correct?
5. is the password correct?
If you have SQL Management Studio installed on your machine, can you connect to the database from there using the username and password?
In Visual Studio, try creating a connection from the Server Explorer window.
Is PC210090 where the db server is located the same machine you are using? It could be a firewall issue.
There are really quite a few reasons as to why its could not be working.
Neill
|
|
|
|
|
Another thing that I am confused by (which happens far too easily.) is if you are using a specific framework?
Why create ServerConnection with the specified ConnectionString which specifies the initial database, and then attempt sqlServer.Databases[strDBName] which is the database name passed into the method?
Neill
|
|
|
|
|
I can download small size of application but could not download big size of application. It shows out of memory.
Below is my code:
string Files = ListBox1.SelectedValue;
byte[] fileBytes = System.IO.File.ReadAllBytes(Files);
WebClient User = new WebClient();
byte[] FileBuffer = User.DownloadData(Files);
if (FileBuffer != null)
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("content-length", FileBuffer.Length.ToString());
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(Files));
context.Response.BinaryWrite(FileBuffer);
context.ApplicationInstance.CompleteRequest();
Could pls anyone help...
|
|
|
|
|
Member 12016106 wrote: byte[] fileBytes = System.IO.File.ReadAllBytes(Files); Do not assume that there is enough memory to hold the entire file.
|
|
|
|
|
So how should declare it to download large size file??
|
|
|
|
|
Simply put, computers don't have unlimited memory. Determine a reasonable buffer size and read the file in chunks of that size, processing each one in turn.
If your data has any kind of structure (either fixed size blocks, or flexible e.g. XML) you should make use of that to work out how to read and process it in smaller pieces.
I can't tell from your sample code what you're trying to do, but it appears you're accessing both local and remote files, either of which could be much larger than your available memory. You need to think through what processing you need to do, and how to achieve it within the limits.
Days spent at sea are not deducted from one's alloted span - Phoenician proverb
|
|
|
|
|
You have several options:
TransmitFile is the preferred method:
string physicalPath = ListBox1.SelectedValue;
if (!string.IsNullOrWhiteSpace(physicalPath))
{
FileInfo fileToSend = new FileInfo(fileToSend);
if (fileToSend.Exists)
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("content-length", fileToSend.Length.ToString());
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlPathEncode(fileToSend.Name));
context.Response.TransmitFile(fileToSend.FullName);
context.Response.Flush();
context.ApplicationInstance.CompleteRequest();
}
}
WriteFile will work in the same way, but can have problems with large files[^].
Reading the file in small blocks requires more code, and won't perform as well as TransmitFile :
int bytesRead;
byte[] buffer = new byte[10000];
using (Stream fileStream = fileToSend.OpenRead())
{
while (context.Response.IsClientConnected && (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
context.Response.OutputStream.Write(buffer, 0, bytesRead);
context.Response.Flush();
}
}
context.ApplicationInstance.CompleteRequest();
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hello,
I am learning to develop in C # on my own which is not an easy thing.
I try to dynamically generate a name for answer my objects.
example:
ComboBox myCombo1 = new ComboBox ();
AND
myCombo1.Text = "Blabla";
What I would like is generated dynamically (myCombo1, myCombo2, myCombo3)
Is this possible or is there a class my question?
Thank you in advance for your help.
Alexandre
|
|
|
|
|
A simple way to do this is to define a Method that creates the ComboBoxes and automatically adds the identifier to their Name. Like this:
private static int ComboBoxCounter = 0;
private const string ComboBoxNameBase = "ComboBox";
public List<ComboBox> TheComboBoxes = new List<ComboBox>();
public ComboBox GetNewComboBox()
{
ComboBox cmbx = new ComboBox {Name = string.Format("{0}{1}",ComboBoxNameBase, ComboBoxCounter++)};
TheComboBoxes.Add(cmbx);
return cmbx;
}
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
|
|
|
|
|
Thank you very mutch.
You know Telerik Framework?
I need help to develop a dynamic desktop with this Framework leaning on a SQL Database
|
|
|
|
|
I have dynamically created textboxes in a loop, and given them names at creation time.
txtProdName.Name = "txtProdName" + i;
pn.Controls.Add(txtProdName);
txtProdDesc.Name = "txtProdDesc" + i;
pn.Controls.Add(txtProdDesc);
The above snippet works fine. Controls are created, and removed as needed.
Now, I would like to go back and read or write information into these textboxes, but I'm at a lost as to how to address them.
I'm trying to do something like:
txtProdName + i.Text = "Blah";
txtProdDesc + i.Text = "Blah2";
Now I know the above code won't work, but wondering if there is someway to do something similar? Or am I totally barking up the wrong tree.
Thanks in advance.
P.S. I haven't found an answer to this anywhere, which leads me to believe I'm at the wrong tree.
|
|
|
|
|
There are several ways to do that - but the easiest is probably to use Controls.Find:
TextBox tbProd = (TextBox)pn.Controls.Find("txtProdName" + i, false).FirstOrDefault();
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Ok, so I follow what you did with the code. Having difficulty in taking it to the next step.
My thoughts are, I should now be able to:
tbProd.Text = "Blah";
However, I get the following error:
'System.NullReferenceException'in Project.exe ("Object reference not set to an instance of an object.")
And to make sure I really do understand what you suggested:
TextBox tbProd = (TextBox)pn.Controls.Find("txtProdName" + i, false).FirstOrDefault();
Creating a new instance of a textbox, called tbProd that is being set to the first control found in the panel, pn with a name of txtProdName + i, and casting that to type textbox.
If I truly understand your code, and the error, it would appear that tbProd didn't actually get the copy I thought it did??
I truly want to thank you for your help.
|
|
|
|
|
The FirstOrDefault method returns null if the collection of objects returned by Find has no elements: so use the debugger to look at the Panel.Controls collection and see exactly what it contains - I suspect that it doesn't have anything, in which case you need to look at the environment in which you are calling Find. When are you doing it, what else have you done, that kind of thing. We can't do that for you - we don't have access to your code!
And BTW:
TextBox tbProd = .... Doesn't create a new instance - it creates a variable that can reference an instance. It's a small but very, very important distinction!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
The WinForms ControlCollection does allow you to use a string Key to access members:
pn.Controls["txtProdName3"].Text = "hello"; When you set the 'Name property of a WinForm Control, you have created the Key (why MS documentation calls it a 'Key baffles me).
So, that is a way you could access the run-time created TextBoxes without keeping a direct reference to them in some data structure.
However, I strongly advise you not to rely on that, and suggest you do something like this:
public List<TextBox> ListOfTextBoxes = new List<TextBox>();
public void createTextBoxes(int howMany)
{
TextBox txtProdName;
TextBox txtProdDesc;
for(int i = 0; i < howMany; i++)
{
txtProdName = new TextBox();
txtProdDesc = new TextBox();
ListOfTextBoxes.Add(txtProdName);
ListOfTextBoxes.Add(txtProdDesc);
txtProdName.Name = "txtProdName " + i;
pn.Controls.Add(txtProdName);
txtProdDesc.Name = "txtProdDesc " + i;
pn.Controls.Add(txtProdDesc);
}
}
ListOfTextBoxes[2].Text = "blah";
pn.Controls["txtProdName3"].Text = "hello";
string tbContent1 = ListOfTextBoxes[0].Text; But, if you are going to use the Index to access the TextBoxes, you can see immediately that you'll have to remember which index to use for TextBoxes that are 'txtProdDesc, and which to use for 'txtProdName.
To make the code clearer, I would use two separate Lists. I would also consider using two Dictionaries of Type <string, TextBox>
If the two TextBoxes are designed to function as a "pair;" I'd consider another data structure, or consider creating a custom UserControl ... all depends on your Application and its scope, purpose, run-time load, etc.
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
modified 15-Oct-15 14:53pm.
|
|
|
|
|
Gentlemen,
I wanted to thank you for your help. Both of you got me going again.
|
|
|
|