file upload fields get the empty value - c#

here is the my problem.I am adding fileuploadfields dynamically and add each fileupload fields to the collection something like this
static List<FileUploadField> fuploadcollection = new List<FileUploadField>();
,so far so good .but when I tring to upload images inside the fileuploadfield,I getting empty fileupload field.but it seems filled "fuploadcollection" collection when I watch it by breakpoint.
here is the my code ;
addfileupload function;
public partial class UserControl1 : System.Web.UI.UserControl
{
static int? _currentflag = 0;
static List<FileUploadField> fuploadcollection = new List<FileUploadField>();
........
........
.........
protected void addImages_Click(object sender, DirectEventArgs e)
{
int? nn = null;
X.Msg.Alert("hello", "hello").Show();
_currentflag = (!string.IsNullOrEmpty(txtcurrentflag.Text)) ? Convert.ToInt32(txtcurrentflag.Text) : nn;
FileUploadField fileUploadField = new FileUploadField()
{
ID = "FileUploadField" + _currentflag,
Width = 280,
Icon = Icon.Add,
ClientIDMode = ClientIDMode.Static,
Text = "Göz at",
FieldLabel = "Resim-" + _currentflag,
Flex = 1,
ButtonText="resim seç"
};
fileUploadField.AddTo(this.pnlResim, true);
if (string.IsNullOrEmpty(txtcurrentflag.Text) || txtcurrentflag.Text == "0")
{
fuploadcollection.Clear();
}
fuploadcollection.Add(fileUploadField);
_currentflag++;
txtcurrentflag.Text = _currentflag.ToString();
}
here is the this part which give the error(coulnt enter the if statement)
* but it seems fuploadcollection filled (forexample count of it shows more then 1 )
foreach (var item in fuploadcollection)
{
if (item.HasFile)
{
string resimadi = UploadImage.UploadImages(item);

If you create dynamic controls you should recreate them during each request. There are some links, which could be helpful:
http://forums.ext.net/showthread.php?19315
http://forums.ext.net/showthread.php?19079
http://forums.ext.net/showthread.php?9224
http://forums.ext.net/showthread.php?16119
http://forums.ext.net/showthread.php?23402

Related

C# DataGridView defined table data that receives data from file

I'm really new to coding so I'm struggling to get an answer for my question directly.
I tried to find answer for my question on many ways (YouTube, stack overflow, google) but couldn't get my program to run correctly.
What I need my program to do is get a value from an m3u file into the appropriate cell on my data table and not read and add absolutely everything.
What I have found online is mainly how to read text/csv/excel and import all the data from the file itself, this is not what I really need or code that i do not understand how to implement for my use, like that question: Reading from .txt file, then exporting data to DataGridView.
I have defined cells that should "suck" the data from the m3u file.
The file m3u file structure is:
#EXTINF:-1 tvg-ID="" tvg-name="==== Example1 ====" tvg-logo="" group-title="",==== Example1 ====
thestreamingsource1.com
#EXTINF:-1 tvg-ID="" tvg-name="==== Example2 ====" tvg-logo="" group-title="",==== Example2 ====
thestreamingsource2.com
#EXTINF:-1 tvg-ID="" tvg-name="==== Example3 ====" tvg-logo="" group-title="",==== Example3 ====
thestreamingsource3.com
#EXTINF:-1 tvg-ID="" tvg-name="==== Example4 ====" tvg-logo="" group-title="",==== Example4 ====
thestreamingsource4.com
And I need the program to only get the following from the value structure:
tvg-ID (It's okay if it's empty).
tvg-name.
tvg-logo (It's okay if it's empty).
group-title.
So far i have the string that reads all the content of the file and the data grid ready to accept data.
The code behind the form is:
public class ThisClass
{
DataGridView my_datagridview = new DataGridView();
DataTable my_datatable = new DataTable();
// Constructor and other methods are in this class,
// but not showed here...
private void btnRead_Click(object sender, EventArgs e)
{
// Some codes are hidden here...
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string sFileName = openFileDialog1.FileName;
string[] alltext = File.ReadAllLines(sFileName);
foreach (string text_line in alltext)
{
// MessageBox.Show(text_line);
}
}
}
}
And the form looks like that:
I'm sorry If the question is already answered but i couldn't find a solution.
Glad if you could help.
Thanks.
This should get you going:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
namespace DataGridView_45378237
{
public partial class Form1 : Form
{
DataGridView my_datagridview = new DataGridView();//the DataGridView which will be put on the form
BindingList<MyDatagridviewEntry> myDataGridviewSource = new BindingList<MyDatagridviewEntry>();//the BindingList from which the DataGridView will pull its data
public Form1()
{
InitializeComponent();
InitializeDataGridView();//set the initial settings of the DataGridView
}
private void InitializeDataGridView()
{
my_datagridview.Location = new Point(this.Location.X + 15, this.Location.Y + 15);//define where to place it in the form(you could obviously just place one directly where you want using the wysiwyg)
this.Controls.Add(my_datagridview);
my_datagridview.AutoSize = true;
my_datagridview.AutoGenerateColumns = true;
my_datagridview.DataSource = myDataGridviewSource;//link the DataGridView with the BindingSource
}
private void btnRead_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\";
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "m3u";
openFileDialog1.Filter = "All files (*.*)|*.*|m3u files (*.m3u)|*.m3u";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string sFileName = openFileDialog1.FileName;
FillDataGridFromFile(sFileName);//send the file to get parsed
}
}
private void FillDataGridFromFile(string incomingFilePath)
{
//empty the list
myDataGridviewSource.Clear();//you may or may not want this... I don't know your full requirements...
//fill the list
using (StreamReader sr = new StreamReader(incomingFilePath))
{
string currentLine = string.Empty;
while ((currentLine = sr.ReadLine()) != null)
{
/*This is not how I would write the production code,
* but for the sake of this example, this format works well
so that you know what is being done and why.*/
string[] splittedString = currentLine.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string f1 = splittedString.Length > 0 ? splittedString[0] : string.Empty;//if splittedString has more than 0 entries, the use entry[0], else use string.empty
string f2 = splittedString.Length > 1 ? splittedString[1] : string.Empty;//if splittedString has more than 1 entries, the use entry[1], else use string.empty
string f3 = GetTVGNameFromString(splittedString[0]);//Extract the text from within the string
string f4 = splittedString.Length > 3 ? splittedString[3] : string.Empty;//if splittedString has more than 3 entries, the use entry[3], else use string.empty
/**/
//add the entry to the BindingSource
myDataGridviewSource.Add(new MyDatagridviewEntry { Col1 = f1, Col2 = f2, Col3 = f3, Col4 = f4 });
}
}
}
private string GetTVGNameFromString(string incomingString)
{
string retval = string.Empty;
Regex rgx = new Regex("tvg-name=\"([^\"]*)\"");//use a grouping regex to find what you are looking for
if (rgx.IsMatch(incomingString))
{
return rgx.Matches(incomingString)[0].Groups[1].Value;
}
return retval;
}
}
public class MyDatagridviewEntry
{
public string Col1 { get; set; }
public string Col2 { get; set; }
public string Col3 { get; set; }
public string Col4 { get; set; }
}
}

datagridview dont let me change the values of the celll

I'm new in c# , but i can do the basics. i need to change all the values of a column and then update the datagrid. The values are in 20170202 format and i want them like 2017-02-02. the method i did works fine but when i try to set the value to the column it wont change.
here is the code:
private void fixAlldates(DataGridView dataGridView2)
{
string aux1 = "";
for (int x = 0; x < dataGridView2.Rows.Count; x++)
{
if (dataGridView2.Rows[x].Cells[4].Value.ToString() != null)
{
aux1 = dataGridView2.Rows[x].Cells[4].Value.ToString();
dataGridView2.Rows[x].Cells[4].Value = fixDate(aux1);
}
if (dataGridView2.Rows[x].Cells[5].Value.ToString() != null)
{
dataGridView2.Rows[x].Cells[5].Value = fixDate(dataGridView2.Rows[x].Cells[5].Value.ToString());
}
dataGridView2.Refresh();
MessageBox.Show(fixDate(aux1); ----> shows result like i want ex: 2017-02-02
MessageBox.Show(dataGridView2.Rows[x].Cells[4].Value.ToString()); ----> shows 2070202
}
}
private string fixDate(string p)
{
if (p == null) return "No especificado";
String fecha = "" + p.Substring(0, 4) + "-" + p.Substring(4, 2) + "-" + p.Substring(6, 2) + "";
return fecha;
}
sorry for my bad english , im a little bit rusty
Edit:
I fill the data with bindingSource.
private void LlenarProductos(string rut)
{
this.rut = rut;
POLbindingSource1.DataSource = null;
dataGridView2.DataSource = null;
DataClasses1DataContext dc = new DataClasses1DataContext();
dc.CommandTimeout = 0;
System.Data.Linq.Table<ASE_PRODUCTOASEGURADO> producto = dc.GetTable<ASE_PRODUCTOASEGURADO>();
var todoprod = from p in producto
where p.RUT == int.Parse(rut)
select new
{
p.POLIZA,
p.SOCIO,
p.SUCURSAL,
p.COD_PROPUESTA,
p.FECHA_ALTA_COTI,
p.FECHA_ALTA_VCTO,
p.NOMBRE_PRODUCTO
};
POLbindingSource1.DataSource = todoprod; // binding source
dataGridView2.DataSource = POLbindingSource1; // filll
this.dataGridView2.Columns["POLIZA"].HeaderText = "Poliza";
this.dataGridView2.Columns["Socio"].HeaderText = "Socio";
this.dataGridView2.Columns["Sucursal"].HeaderText = "Sucursal";
this.dataGridView2.Columns["COD_PROPUESTA"].HeaderText = "Propuesta";
this.dataGridView2.Columns["FECHA_ALTA_COTI"].HeaderText = "Fecha Cotizacion";
this.dataGridView2.Columns["FECHA_ALTA_VCTO"].HeaderText = "Fecha Vencimiento";
this.dataGridView2.Columns["NOMBRE_PRODUCTO"].HeaderText = "Producto";
// fixAlldates(dataGridView2);
}
From msdn https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.value(v=vs.110).aspx.
The Value property is the actual data object contained by the cell.
So basically the line MessageBox.Show(dataGridView2.Rows[x].Cells[4].Value.ToString()); is getting the value of the underlying data, whereas MessageBox.Show(fixDate(aux1); is actually formatting the date as you require.
You're overlooking the fact that although you're seeing the data in the grid in a specific way, you're not actually changing the data itself.
UPDATE
To actually edit the data in a cell see here

Clearing controls from a FlowLayoutPanel

I'm trying to remove the controls of the FlowLayoutPanel in the code that is attached below. The problem is that I use a search function in the same frame, so I can't find other objects without clearing it first. I already tried:
fPanelUpperMainScreen.Controls.Remove(a);
This is my method that I am working on.
public void GetArtistLayout()
{
ArtistInformation a = new ArtistInformation();
fPanelUpperMainScreen.Controls.Add(a);
int valueInt = int.Parse(tBMainScreen_Search.Text);
a.pictureBox1.ImageLocation = ar.GetArtist(valueInt).artistPic;
a.lblArtistInformation_ArtistName.Text = ar.GetArtist(valueInt).artistName;
var reviews = rr.getMatchingReviewsArtist(valueInt);
foreach (var review in reviews)
{
UserControl1 u = new UserControl1();
u.lblUser.Text = review.username;
u.lblComment.Text = review.comments;
u.lblDate.Text = review.date;
u.lblRating.Text = review.rating.ToString();
a.fpArtistInformation_Reviews.Controls.Add(u);
}
}

C# how to make the stored file to cap at 100 items?

I'm trying to make a small program that take the user input and store it on a file but I want that file to cap at 100 elements:
Let's say the user add 100 names and the next name the user add it will show a message "List is full"
Here is the code I have done so far:
public Form1()
{
InitializeComponent();
}
private string SongName, ArtistName;
public void Registry()
{
List<Name> MusicList = new List<Name>(); //Create a List
MusicList.Add(new Name(SongName = txtSongName.Text, ArtistName = txtArtistName.Text)); //Add new elements to the NameClass
//check if the input is correct
if (txtSongName.TextLength < 1 || txtArtistName.TextLength < 1)
{
Info info = new Info();
info.Show();
}
else //if input is correct data will be stored
{
//Create a file to store data
StreamWriter FileSaving = new StreamWriter("MusicList", true);
for (int i = 0; i < MusicList.Count; i++)
{
string sName = MusicList[i].songName; //Create new variable to hold the name
string aName = MusicList[i].artistName; //Create new variable to hold the name
FileSaving.Write(sName + " by "); //Add SongName to the save file
FileSaving.WriteLine(aName); //Add ArtistName to the save file
}
FileSaving.Close();
}
}
private void btnEnter_Click(object sender, EventArgs e)
{
Registry();
//Set the textbox to empty so the user can enter new data
txtArtistName.Text = "";
txtSongName.Text = "";
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
private const int MAX_STORED_SONGS = 100;//as class level field
for (int i = 0; i < MusicList.Count && i < MAX_STORED_SONGS; i++)
//...after the loop
if( MusicList.Count > MAX_STORED_SONGS )
errorMessageLabel.Text = "List is full, only 100 items added"
I'm not sure what your list picker looks like, but you would probably want to actually prevent them from selecting more than 100 items, by using some javascript/validation client side before the page is submitted.
What is not clear about your code, is while it appears the user submits a single song, you create a new empty MusicList, add a single item to it, but you loop through it as if there is more than one item. Perhaps you should begin by reading the file to determine how many songs are in it, so you can determine when it is at 100 songs.
You may wish to try using xml to give your data some structure.
If you want to keep it in the current format your only option is to count NewLines in your file and see if that count plus any new items in your music list puts you over your limit.
List<string> lines = new List<string>(System.IO.File.ReadAllLines(MyFile));
lines.Add(sName + " by " + aName);
int lineCount = lines.Count;
//limit reached
if(lineCount > 100 )
{
//TODO: overlimit code
} else {
System.IO.File.WriteAllLines(MyFile, lines.ToArray());
}

Dynamic names for panels

I'm working on a program that is supposed to use with multiple users. I'm getting the users from a database. So far so good...
I'm dynamically adding a panel to the form, which would hold some data. I'm using this piece of code to achieve that:
string panel_name = "email_in_" + user_credentials[counter_snel][0];
Panel new_user_panel = new Panel();
new_user_panel.AutoSize = true;
new_user_panel.Dock = System.Windows.Forms.DockStyle.Fill;
new_user_panel.Location = new System.Drawing.Point(0, 0);
new_user_panel.Name = panel_name;
new_user_panel.Visible = false;
Label new_item = new Label();
new_item.AutoSize = true;
new_item.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
string new_item_text = string.Format("{0,0}\n{1,0}\n{2,0}", user_credentials[counter_snel][1], user_credentials[counter_snel][2],user_credentials[counter_snel][9]);
new_item.Text = new_item_text;
splitContainer2.panel_name.Controls.Add(new_item);
as you will probably notice, this line of code is not working:
splitContainer2.panel_name.Controls.Add(new_item);
How can I achieve this, so when I want to make panel email_in_1 visible, I can use that, and make email_in_8 not visible?
### EDIT 1 ###
the code now looks like this:
string panel_name = "email_in_" + user_credentials[counter_snel][0];
Panel new_user_panel = new Panel();
new_user_panel.AutoSize = true;
new_user_panel.Dock = System.Windows.Forms.DockStyle.Fill;
new_user_panel.Location = new System.Drawing.Point(0, 0);
new_user_panel.Name = panel_name;
new_user_panel.Visible = true;
user_email_in_panels.Add(new_user_panel);
splitContainer2.Panel1.Controls.Add(new_user_panel);
Label new_item = new Label();
new_item.AutoSize = true;
new_item.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
string new_item_text = string.Format("{0,0}\n{1,0}\n{2,0}", user_credentials[counter_snel][1], user_credentials[counter_snel][2],user_credentials[counter_snel][9]);
new_item.Text = new_item_text;
int aantal_panels = 0;
foreach (Panel panel in user_email_in_panels) {
aantal_panels++;
}
int counter_1 = 0;
foreach (Panel panel in user_email_in_panels) {
if(counter_1 == (aantal_panels -1)){
MessageBox.Show("We are here");
panel.Controls.Add(new_item);
splitContainer1.Panel1.Controls.Add(panel);
}
counter_1++;
}
But somehow, i don't see any labels shown in the form... am i missing something? The messsagebox with the text We are Here is shown, so it come's to the add statement....
and i've got an another question besides my first question. My question is, how can i make the counter of the list better?
### Edit for Sean Vaughn
i've updated it to this:
public class MyPanelClass {
public string Name {
get;
set;
}
public bool Visible {
get;
set;
}
public string YourLabelsText {
get;
set;
}
}
Label new_item = new Label();
new_item.AutoSize = true;
new_item.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
string new_item_text = string.Format("{0,0}\n{1,0}\n{2,0}", user_credentials[counter_snel][1], user_credentials[counter_snel][2], user_credentials[counter_snel][9]);
new_item.Text = new_item_text;
Panel base_panel = new Panel(); //this is your base panel, you don't need to add this line of code because Visual Studio will do that for you.
List<MyPanelClass> myPanelList = new List<MyPanelClass>(); //this will keep records of all of your panels.
MyPanelClass panel_name = new MyPanelClass();
panel_name.Name = "email_in_" + user_credentials[counter_snel][0]; ;
panel_name.Visible = true;
panel_name.YourLabelsText = string.Format("{0,0}\n{1,0}\n{2,0}", user_credentials[counter_snel][1], user_credentials[counter_snel][2], user_credentials[counter_snel][9]);
//Now add the new created panel to the list.
myPanelList.Add(panel_name);
base_panel.Name = myPanelList[counter_snel].Name;
base_panel.Visible = myPanelList[counter_snel].Visible; //You probably don't need this because base_panel will always be visible
new_item.Text = myPanelList[counter_snel].YourLabelsText;
But i still doesn't see anything...
Does it matter that it execudes in an public void??? i don't think so, but it want to elliminate all the possibilities...
Use a List that will keep track of all the panels.
List<Panel> myPanels = new List<Panel>();
Whenever you need to add a panel, do this:
mypanels.Add(yourPanel);
Now, for the other problem, create a function like this:
private void HideAllOtherPanels(List<Panel> panelList, Int index /*the index of the panel you want to show*/)
{
foreach(Panel panel in panelList)
if(panel.Visible) panel.Hide();
panelList[index].Show();
}
I see you are creating a lot of new panels. My advice, don't do that, you're giving a lot of load to the system.
Instead make a class.
public class MyPanelClass
{
public string Name
{
get; set;
}
public bool Visible
{
get; set;
}
public string YourLabelsText
{
get; set;
}
}
After creating the class, create a base_panel on your form that will change it's contents based on the your intentions.
And then, all you need to do is change the panel's content rather than creating a new Panel. Store the other panels data in a List<MyPanelClass>.
So you'll be doing this:
Panel base_panel = new Panel(); //this is your base panel, you don't need to add this line of code because Visual Studio will do that for you.
List<MyPanelClass> myPanelList = new List<MyPanelClass>(); //this will keep records of all of your panels.
MyPanelClass panel_name = new MyClassPanel();
panel_name.Name = "email_in_" + user_credentials[counter_snel][0];;
panel_name.Visible = false;
panel_name.YourLabelsText = string.Format("{0,0}\n{1,0}\n{2,0}", user_credentials[counter_snel][1], user_credentials[counter_snel][2],user_credentials[counter_snel][9]);
//Now add the new created panel to the list.
myPanelList.Add(panel_name);
Now whenever you need to activate a stored Panel, just do this:
base_panel.Name = myPanelList[yourPanelsIndex].Name;
base_panel.Visible = myPanelList[yourPanelsIndex].Visible; //You probably don't need this because base_panel will always be visible
yourLabel.Text = myPanelList[yourPanelsIndex].YourLabelsText;
This code is much less bulky on the machine and is easy to handle too.
I'd try something like this to add an item.
var panel = splitContainer2.Controls.FirstOrDefault(p => p is Panel && ((Panel)p).Name == panel_name);
if(panel != nul)
{
panel.Controls.Add(new_item);
}
To hide a particular panel given panel_name:
foreach(var control in splitContainer2.Controls)
{
if(control is Panel)
{
((Panel)control).Visible = ((Panel)control).Name == panel_name;
}
}

Categories

Resources