Technology: SharePoint/MOSS 2007 --
IDE: Visual Studio 2008 --
Language: C#
I have created a SharePoint/MOSS 2007 web part that displays a list of log files.
The log files are rendered on screen as LinkButtons. The LinkButtons are within a DataTable that is set as the data source of a SPGridView and bound to it.
This SPGridView object is then added to the 'Controls' within the overridden "CreateChildControls()" method of the web part.
I am utilising the following "DownloadAssistant" helper class to display a specified file.
It's "DownloadFile" method is called from the '.Click' event of each LinkButton.
using System;
using System.Web;
/// <summary>
/// A class that helps to build download buttons/links on the fly
/// </summary>
static public class DownloadAssistant
{
static public void DownloadFile(string filePath)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Concat("attachment; filename=", filePath));
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(filePath);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
}
After one LinkButton is clicked on screen, I receive the download pop up window as expected and can go ahead and open the first log file. However after this first log file is opened, i.e. after the first LinkButton click event is triggered, I cannot trigger any other .Click event - it is as it I need to post back to the screen. When I click on any of the other LinkButtons nothing happens?
The Web Part code:
namespace LogRetrievalWebPart
{
[Guid("fd243ec2-83e3-4bad-af5e-c5c16acbc6dd")]
public class LogRetrievalWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
// Member variables prefixed with "m_"
private Label m_InfoLbl;
private SPGridView m_GridView;
private DataTable m_LogFileDataTable;
private DropDownList m_DirectoryDropDown;
private const String DROPDOWN_OPTION_DEFAULT = "---";
private const String DROPDOWN_OPTION_TRACE_LOGS = "Trace Logs";
private const String DROPDOWN_OPTION_BATCH_LOGS = "Batch Logs";
private const String DROPDOWN_OPTION_OTHER_LOGS = "Other Logs";
public LogRetrievalWebPart()
{
this.ExportMode = WebPartExportMode.All;
}
protected override void CreateChildControls()
{
EnsureChildControls();
base.CreateChildControls();
m_InfoLbl = new Label();
Label dropDownLbl = new Label();
dropDownLbl.Text = " Please select a directory: ";
this.Controls.Add(dropDownLbl);
m_DirectoryDropDown = new DropDownList();
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_DEFAULT);
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_TRACE_LOGS);
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_BATCH_LOGS);
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_OTHER_LOGS);
m_DirectoryDropDown.TextChanged += new EventHandler(directoryDropdown_TextChanged);
m_DirectoryDropDown.AutoPostBack = true;
m_LogFileDataTable = new DataTable("LogFiles");
AddColums();
m_GridView = new SPGridView();
m_GridView.AutoGenerateColumns = false;
BoundField idField = new BoundField();
idField.DataField = "ID";
idField.HeaderText = "ID";
m_GridView.Columns.Add(idField);
TemplateField colName = new TemplateField();
colName.HeaderText = "Log File Name";
colName.SortExpression = "LogFileName";
colName.ItemTemplate = new LinkTemplate("LogFileName", "Path");
m_GridView.Columns.Add(colName);
this.Controls.Add(m_DirectoryDropDown);
this.Controls.Add(m_InfoLbl);
this.Controls.Add(m_GridView);
this.Load += new EventHandler(LogRetrievalWebPart_Load);
this.PreRender += new EventHandler(LogRetrievalWebPart_PreRender);
}
void LogRetrievalWebPart_Load(object sender, EventArgs e)
{
EnsureChildControls();
}
protected void directoryDropdown_TextChanged(object sender, EventArgs e)
{
ViewState["LogRetrieval"] = null;
String selectedDirectoryName = m_DirectoryDropDown.SelectedItem.Text;
if (DROPDOWN_OPTION_TRACE_LOGS.Equals(selectedDirectoryName))
{
m_InfoLbl.Text = " *** TRACE Logs: *** ";
GetLogFiles("LogFiles/TraceLogs");
}
else if (DROPDOWN_OPTION_BATCH_LOGS.Equals(selectedDirectoryName))
{
m_InfoLbl.Text = " *** BATCH Logs: *** ";
GetLogFiles("PortalExecutables/Logs");
}
else if (DROPDOWN_OPTION_OTHER_LOGS.Equals(selectedDirectoryName))
{
m_InfoLbl.Text = " *** OTHER Logs: *** ";
GetLogFiles("PortalExecutables/GMExecutables");
}
else
{
m_InfoLbl.Text = " *** No Logs to display for this selection!!! *** ";
}
ViewState["LogRetrieval"] = m_LogFileDataTable;
m_GridView.DataSource = m_LogFileDataTable;
m_GridView.DataBind();
}
private void GetLogFiles(string aSelectedDirectory)
{
string directoryPath = HttpContext.Current.Server.MapPath(ResolveUrl("/LogFiles/" + aSelectedDirectory));
DirectoryInfo directory = new DirectoryInfo(directoryPath);
FileInfo[] files = directory.GetFiles();
int count = 1;
foreach (FileInfo fileInfo in files)
{
string fullFileName = fileInfo.FullName;
string fileName = fileInfo.ToString();
AddRow(count, fileName, fullFileName);
count++;
}
}
private void AddRow(int id, string logFileName, string fullFileName)
{
DataRow newRow = m_LogFileDataTable.Rows.Add();
newRow["ID"] = id;
newRow["LogFileName"] = logFileName;
newRow["Path"] = fullFileName;
}
private void AddColums()
{
DataColumn idCol = m_LogFileDataTable.Columns.Add("ID", typeof(Int32));
idCol.Unique = true;
m_LogFileDataTable.Columns.Add("LogFileName", typeof(String));
m_LogFileDataTable.Columns.Add("Path", typeof(String));
}
public void LogRetrievalWebPart_PreRender(object sender, EventArgs e)
{
if (this.Page.IsPostBack)
{
if (ViewState["LogRetrieval"] != null)
{
m_LogFileDataTable = (DataTable)ViewState["LogRetrieval"];
m_GridView.DataSource = m_LogFileDataTable;
m_GridView.DataBind();
}
}
}
public class LinkTemplate : ITemplate
{
string logFileName;
string logFilePath;
public LinkTemplate(string fieldName, string path)
{
logFileName = fieldName;
logFilePath = path;
}
public void InstantiateIn(Control container)
{
LinkButton link = new LinkButton();
container.Controls.Add(link);
link.DataBinding += new EventHandler(link_DataBinding);
link.Click += new EventHandler(link_Click);
}
private void link_DataBinding(Object sender, EventArgs e)
{
LinkButton link = (LinkButton)sender;
DataRowView dataRow = (DataRowView)((SPGridViewRow)link.NamingContainer).DataItem;
link.Text = dataRow[logFileName].ToString();
link.CommandArgument = dataRow[logFilePath].ToString();
}
private void link_Click(object sender, EventArgs e)
{
LinkButton link = (LinkButton)sender;
DownloadAssistant.DownloadFile(link.CommandArgument);
}
}
}
}
I found a solution.
I had to:
Set the button's client-side click event to: "exportRequested=true;"
Register the some JavaScript: For exact details, refer to:
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/55136e4e-e1f7-4a79-9b75-be09cd5594c2
Related
Hi i am creating dropdownlist dynamically but on post back it is loosing the value and i am unable to get values on button click event.
private void CreateDropdownListEmployee(string id,Panel pnl, DataTable dt)
{
DropDownList drp = new DropDownList();
drp.ID = id;
drp.CssClass = "activeuserTxt";
drp.ClientIDMode = ClientIDMode.Static;
drp.DataSource = dt;
drp.DataTextField = "name";
drp.DataValueField = "id";
drp.DataBind();
pnl.Controls.Add(drp);
}
For the dynamic texbox i am using the below code on PAge_Init
protected void Page_Init(object sender, EventArgs e)
{
try
{
int SNID = 0;
List<string> keysNetmr = Request.Form.AllKeys.Where(key => key.Contains("txt")).ToList();
foreach (string key in keysNetmr)
{
this.CreateTextBox("txtNermr" + SNID, 100, pnlSN);
SNID++;
}
}
catch (Exception ex) { }
}
private void CreateTextBox(string id, int width, Panel pnl)
{
TextBox txt = new TextBox();
txt.ID = id;
txt.Width = width;
txt.Attributes.Add("autocomplete", "off");
txt.CssClass = "activeuserTxt";
pnl.Controls.Add(txt);
}
Can anyone help me on this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GST.Masters
{
public partial class Customers : Heptanesia.Winforms.Ui.Forms.MainUC
{
public static string recCode
{ get; set; }
public string RC;
public bool insertFlag;
public Data.GSTDb.CustomersRow r;
public Data.GSTDb.CustomersGSTNosRow gr;
public Data.GSTDb.CustomersDataTable dt = new Data.GSTDb.CustomersDataTable();
public Customers()
{
InitializeComponent();
recCode = Guid.NewGuid().ToString();
this.Load += new EventHandler(this.Customers_Load);
this.Ts.SaveClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SaveClickedEventHandler(this.Ts_SaveClicked);
this.Ts.AddNewClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.AddNewClickedEventHandler(this.Ts_AddNewClicked);
this.Ts.SearchClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SearchClickedEventHandler(this.Ts_SearchClicked);
this.DgGST.CellValidated += (sender, e) =>
{
string name = this.DgGST.Columns[e.ColumnIndex].Name;
if (name == "DGCCountryCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.statesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCStateCode"].Value = null;
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
else if (name == "DGCStateCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.citiesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
};
}
private void Ts_AddNewClicked(object sender, EventArgs e)
{
this.gSTDb.Customers.Rows.Clear();
r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter CGT = new Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter();
CGT.FillByParentCode(gSTDb.CustomersGSTNos, r.RecCode);
}
private void Ts_SearchClicked(object sender, EventArgs e)
{
Heptanesia.Winforms.Ui.Forms.SearchForm sf = new Heptanesia.Winforms.Ui.Forms.SearchForm();
sf.DataSource = new Data.GSTDbTableAdapters.CustomersTableAdapter().GetData();
sf.DisplayColumns = new string[] { "Name" };
sf.DisplayHeaders = new string[] { "Customers Name" };
sf.DisplayWidths = new int[] { 200 };
if (sf.ShowDialog(this) == DialogResult.OK)
{
this.RC = sf.ReturnRow["RecCode"].ToString();
this.customersTableAdapter.FillByRecCode(this.gSTDb.Customers, RC);
}
}
private void Ts_SaveClicked(object sender, EventArgs e)
{
string message = "Error: ";
try
{
this.customersBindingSource.EndEdit();
//if (this.DgGST.CurrentRow.DataBoundItem != null)
this.fkCustomerGSTNosCustomersBindingSource.EndEdit();
if (this.gSTDb.Customers.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.customersBindingSource, this.gSTDb.Customers.GetErrors()[0]);
else if (this.gSTDb.CustomersGSTNos.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.fkCustomerGSTNosCustomersBindingSource, this.gSTDb.CustomersGSTNos.GetErrors()[0]);
else
{
this.gSTDb.Customers.BeforeSave();
this.gSTDb.CustomersGSTNos.BeforeSave();
Data.GSTDbTableAdapters.TableAdapterManager tm = new Data.GSTDbTableAdapters.TableAdapterManager();
tm.CustomersTableAdapter = this.customersTableAdapter;
tm.CustomersGSTNosTableAdapter = this.customersGSTNosTableAdapter;
tm.UpdateAll(this.gSTDb);
message = "Record(s) Saved Successfully";
}
}
catch (Exception ex)
{
message += ex.Message;
}
MessageBox.Show(message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Customers_Load(object sender, EventArgs e)
{
this.FormIsLoading = true;
this.customersTableAdapter.Fill(this.gSTDb.Customers);
this.customersGSTNosTableAdapter.Fill(this.gSTDb.CustomersGSTNos);
this.countriesTableAdapter.Fill(this.gSTDb.Countries);
this.statesTableAdapter.Fill(this.gSTDb.States);
this.citiesTableAdapter.Fill(this.gSTDb.Cities);
this.gSTDb.Customers.Rows.Clear();
if (this.gSTDb.Customers.Rows.Count == 0)
{
Data.GSTDb.CustomersRow r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
}
this.FormIsLoading = false;
}
private void DgGST_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Exception is ArgumentException)
{
object value = DgGST.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (!((DataGridViewComboBoxColumn)DgGST.Columns[e.ColumnIndex]).Items.Contains(value))
{
((DataGridViewComboBoxCell)DgGST[e.ColumnIndex, e.RowIndex]).Value = DBNull.Value;
//((DataGridViewComboBoxColumn)dgv.Columns[e.ColumnIndex]).Items.Add(value);
e.ThrowException = false;
}
}
else
{
MessageBox.Show(e.Exception.Message);
e.Cancel = true;
}
}
}
}
I am developing one simple invoice application in which I am having a simple Customer screen module.A Customer can have any number of GST records in the Datagridview.The Screen is based on Customer Masters(Textboxes) and Customers Master Details(Datagridview) relationship through foreign keys. And I am Using Strongly Typed Dataset in this project as a xsd file.This Screen has 3 buttons i.e.New,Save and Find toolstrip menu.
When I start adding records after clicking on New Buttonstrip and and save ,it saves it successfully and when I press New Ideally it should clear the rows.The main issue here is that it is not clearing the rows??
I am enclosing the cs file here.
What I have tried:
Everything as I can Do.
Clearing the Rows through Rows.Clear(); 2) I tried clearing
Binding Source and DataGridview after setting it null.
Nothing Worked.
I made it so that you can open a dll and load it onto a listbox as a clickable item when once clicked, the plugin would load and you can execute that plugin.
I added a clear button that is suppose to clear the app of the currently loaded plugins.
It clears everything off the app but when I go to load them again, it loads duplicates.
How do I clear the assembly too so that when i reload a plugin, it will not duplicate??
Code Behind:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using PluginContracts;
using System;
using System.IO;
using Microsoft.Win32;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.Diagnostics;
using System.Linq;
namespace SimplePlugin
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Dictionary<string, IPlugin> _Plugins; // move to class scope
public MainWindow()
{
InitializeComponent();
_Plugins = new Dictionary<string, IPlugin>();
}
private void AssembleComponents(object sender)
{
string selection = "";
if (sender is ListBox)
{
if (((ListBox)sender).SelectedValue != null)
selection = ((ListBox)sender).SelectedValue.ToString();
}
string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
DirectoryCatalog cat = new DirectoryCatalog(path);
//ICollection<IPlugin> plugins = PluginLoader.LoadPlugins("Plugins");
ICollection<IPlugin> plugins = GenericPluginLoader<IPlugin>.LoadPlugins("Plugins");
foreach (var item in plugins)
{
//add only if not already present
if (!_Plugins.ContainsKey(item.Name))
{
string dllName = GetDLLName(item.Name);
Button b = new Button()
{
Name = dllName.Replace(".", "").ToUpper(),
Content = item.Name,
Visibility = System.Windows.Visibility.Hidden
};
b.Click += b_Click;
PluginGrid.Children.Add(b);
_Plugins.Add(item.Name, item);
// this.PluginGrid.Children.Clear();
//by Vasey
}
}
// make visible the selected plugin button
foreach (var ctl in PluginGrid.Children)
{
if (ctl is Button)
{
Button button = (Button)ctl;
if (button.Name.Equals(selection.Replace(".", "").ToUpper()))
{
button.Visibility = System.Windows.Visibility.Visible;
}
else
{
button.Visibility = System.Windows.Visibility.Hidden;
}
}
}
}
private void b_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
string key = b.Content.ToString();
if (_Plugins.ContainsKey(key))
{
IPlugin plugin = _Plugins[key];
plugin.Do();
}
}
}
private void addPlugin_Click(object sender, RoutedEventArgs e)
{
var fileDialog = new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.Filter = "All files (*.*)|*.*|DLL files (*.dll)|*.dll|CS Files (*.cs)|*.cs";
if (fileDialog.ShowDialog() == true)
{
string filename = fileDialog.FileName;
var ext = System.IO.Path.GetExtension(filename);
// ListBox lbFiles = new ListBox();
//this.Controls.Add(lbFiles);
//lbFiles.Size = new System.Drawing.Size(200, 100);
//lbFiles.Location = new System.Drawing.Point(10, 10);
lbFiles.Items.Add(System.IO.Path.GetFileName(filename));
//
CopyToDir(filename);
}
}
private void CopyToDir(string filename)
{
// txtBox.Text = "Hello World";
string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
Console.WriteLine(path);
//Check the directory exists
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
try
{
FileInfo fi = new FileInfo(filename);
if (!File.Exists(System.IO.Path.Combine(path, fi.Name)))
{
File.Copy(fi.FullName, System.IO.Path.Combine(path, fi.Name));
}
}
catch (Exception ex)
{
throw ex;
}
}
// Get linkage between ListBox's DLL name list and the loaded plugin names
string GetDLLName(string name)
{
string ret = "";
name = name.Replace(" ", ""); // strip spaces
Assembly asm = AppDomain.CurrentDomain.GetAssemblies().
SingleOrDefault(assembly => assembly.GetName().Name == name);
if (asm != null)
{
ret = Path.GetFileName(asm.Location);
}
return ret;
}
private void lbFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
AssembleComponents(sender);
}
private void ClearBtn_Click(object sender, RoutedEventArgs e)
{
lbFiles.Items.Clear();
_Plugins = new Dictionary<string, IPlugin>();
}
}
}
I just had to add this function to the clearBtn method
//Clears the Assembly
this.PluginGrid.Children.Clear();
Before
private void ClearBtn_Click(object sender, RoutedEventArgs e)
{
lbFiles.Items.Clear();
_Plugins = new Dictionary<string, IPlugin>();
}
After
private void ClearBtn_Click(object sender, RoutedEventArgs e)
{
// Clears the ListBox
lbFiles.Items.Clear();
//Clears the Assembly
this.PluginGrid.Children.Clear();
//Loads next Assembly
_Plugins = new Dictionary<string, IPlugin>();
}
I am currently working on a small DB project in which I have tried implementing a browser for image so that they can be saved for each player accordingly.
I am particularly struggling with wring the path of the image to a string, and the storing that string into the arraylist which will then be used to load the file by using the path stored in that arraylist. As you see in the code I have tried to assign the OpenFd.FileName to a string called pathToImage but it doesn't work, the string remains empty after a quick debug check using MessageBox.Show(pathToImage)
Can anyone help me?
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.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assignment1_Template2
{
public partial class Form1 : Form
{
// =======================The data Structure ===========================
// ========Uses [SERIALIZABLE] to allow simple loading/saving ==========
[Serializable]
private struct myStruct
{ // The "constructor". Fills data structure with default values
public myStruct(int playerId)
{
uniquePlayerId = new int[playerId];
playerIgName = "";
contactStreet = "";
contactTown = "";
contactPostcode = "";
contactEmail = "";
contactTelephone = "";
imagePath = "";
for (int i = 0; i < playerId; ++i) uniquePlayerId[i] = 0;
}
// The data types of the struct
public int[] uniquePlayerId;
public string playerIgName;
public string contactStreet;
public string contactTown;
public string contactPostcode;
public string contactEmail;
public string contactTelephone;
public string imagePath;
}
// ================== End of data Structure definition ===================
// =======================================================================
// ================ Global Variables used in the Program =================
private ArrayList dataList; // This is the main data collection
private int currentEntryShown = 0; // current myStruct on display
private int numberOfEntries = 0; // total number of myStructs
private string filename = "C:\\test.dat"; // path of the file being read in
public string pathToImage = "";
public string pathToImagePlaceholder = "";
// =======================================================================
// ================== STARTING POINT FOR THE PROGRAM =====================
public Form1()
{
// Brings up the window.
InitializeComponent();
// Create the ArrayList
dataList = new ArrayList();
// Call methods implemented below
LoadData();
ShowData();
UpdatePrevNextBtnStatus();
}
// =========================================================================
// =================== END OF STARTING POINT FOR PROGRAM ===================
// ========= All further events are now triggered by user actions ==========
// =========================================================================
// =========================================================================
// ========================= BUTTON ACTION HANDLERS ========================
// =========================================================================
private void showPreviousBtn_Click(object sender, EventArgs e)
{
--currentEntryShown;
ShowData();
UpdatePrevNextBtnStatus();
}
private void showNextBtn_Click(object sender, EventArgs e)
{
++currentEntryShown;
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void addNewPlayerBtn_Click(object sender, EventArgs e)
{
++numberOfEntries; // "Add" clicked: we need to create one more entry
currentEntryShown = numberOfEntries - 1; // scroll to an empty record at the end
// Create a new data structure, its constructor will fill it with default values
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct); // add the frshly created struct to the ArrayList
ShowData(); // display
addNewPlayerBtn.Enabled = true; // can't do this again before saving
UpdatePrevNextBtnStatus();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
SaveData(); // Call the Save() method implemented below
addNewPlayerBtn.Enabled = true; // After saving we can add another new record
UpdatePrevNextBtnStatus(); // Set 'Next' and 'Previous' button appearance
}
// =========================================================================
// =========================================================================
// ================ HANDLE DATA CHANGES BY USER ============================
// =========================================================================
// If the text box string is changed by the user, update
private void playerIdBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
dataList[currentEntryShown] = aNewStruct;
}
private void playerIgNameBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.playerIgName = playerIgNameBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactStreetBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactStreet = contactStreetBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTownBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTown = contactTownBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactPostcode = contactPostcodeBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactEmailBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactEmail = contactEmailBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTelephone = contactTelephoneBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
// =========================================================================
// ================= HELPER METHODS FOR DISPLAYING DATA ====================
// =========================================================================
private void ShowData()
{
playerIdBox.Text = ((myStruct)dataList[currentEntryShown]).uniquePlayerId[0].ToString();
playerIgNameBox.Text = ((myStruct)dataList[currentEntryShown]).playerIgName;
contactStreetBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactStreet;
contactTownBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTown;
contactPostcodeBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactPostcode;
contactEmailBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactEmail;
contactTelephoneBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTelephone;
pathToImagePlaceholder = "" + ((myStruct)dataList[currentEntryShown]).imagePath;
MessageBox.Show(pathToImagePlaceholder);
try
{
playerPictureBox.Image = Image.FromFile(pathToImagePlaceholder);
}
catch
{
return;
}
}
private void UpdatePrevNextBtnStatus()
{
if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
else showPreviousBtn.Enabled = false;
if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
else showNextBtn.Enabled = false;
label1.Text = "Player ID";
label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
}
// =========================================================================
// =========================================================================
// =============== HELPER METHODS FOR LOADING AND SAVING ===================
// =========================================================================
private void SaveData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, dataList);
MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Could not serialise to " + filename,
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
MessageBox.Show("Could not open " + filename +
" for saving.\nNo access rights to the folder, perhaps?",
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void LoadData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
try
{
BinaryFormatter bf = new BinaryFormatter();
dataList = (ArrayList)bf.Deserialize(fs);
currentEntryShown = 0;
numberOfEntries = dataList.Count;
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename +
"\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
"FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
fs.Close(); // close file
Environment.Exit(1); // crash out
}
fs.Close();
}
catch
{
if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
"FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
// No data exist yet. Create a first entry
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct);
numberOfEntries = 1;
currentEntryShown = 0;
}
}
}
// =========================================================================
// =========================================================================
// ====================== HELPER METHODS FOR SORTING =======================
// =========================================================================
// This function will sort by player name by using the PlayerNameComparer below
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
dataList.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
// Overriding (= overwriting) the default IComparer
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((myStruct)x).playerIgName.CompareTo(((myStruct)y).playerIgName);
}
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveData();
UpdatePrevNextBtnStatus();
}
private void deletePlayerBtn_Click(object sender, EventArgs e)
{
dataList.RemoveAt(currentEntryShown);
SaveData();
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
Form searchForm = new Form1();
searchForm.Show();
}
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
pathToImage = OpenFd.FileName;
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = pathToImage;
dataList[currentEntryShown] = aNewStruct;
// save the FileName to a string.
}
MessageBox.Show(pathToImage);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
Set pathToImage after the ShowDIalog has completed, not before:
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
pathToImage = OpenFd.FileName; ...
I could be wrong because reading all that wall of code requires too much time, but your last method should be
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
// REMOVED HERE .... pathToImage = OpenFd.FileName
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = OpenFd.FileName; // Changed this line...
dataList[currentEntryShown] = aNewStruct;
}
// no much sense this here if the user cancel the dialogbox
// MessageBox.Show(pathToImage);
}
I have a Windows Form application. What this application does, is let the user browse to a drive/folder they wish to have files renamed for. This app renames files that have "invalid" characters (that are defined in a RegEx pattern).
What i want to happen here is, after the user decides which drive/folder to use, a datagridview pops up showing the user files in the drive/folder that are going to be renamed. The user then clicks a button to actually rename the files. I'm having trouble though getting the code for my button in DriveRecursion_Results.cs set up. Can anybody help me? Code plz -- i'm extremely new to this and need syntax to look at to understand.
Form1 code:
namespace FileMigration2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderSelect("Please select:");
}
public string FolderSelect(string txtPrompt)
{
//Value to be returned
string result = string.Empty;
//Now, we want to use the path information to population our folder selection initial location
string initialPathDir = (#"C:\");
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(initialPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
{
retPath = "";
}
DriveRecursion_Results dw = new DriveRecursion_Results();
dw.Show();
dw.DriveRecursion(retPath);
result = retPath;
}
return result;
}
}
}
DriveRecursion_Results.cs code: [the button is in here that i need help with!]
namespace FileMigration2
{
public partial class DriveRecursion_Results : Form
{
public DriveRecursion_Results()
{
InitializeComponent();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DriveRecursion(string retPath)
{
//recurse through files. Let user press 'ok' to move onto next step
// string[] files = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
//string replacement = "";
Regex regEx = new Regex(pattern);
string[] fileDrive = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
List<string> filePath = new List<string>();
dataGridView1.Rows.Clear();
try
{
foreach (string fileNames in fileDrive)
{
if (regEx.IsMatch(fileNames))
{
string fileNameOnly = Path.GetFileName(fileNames);
string pathOnly = Path.GetDirectoryName(fileNames);
DataGridViewRow dgr = new DataGridViewRow();
filePath.Add(fileNames);
dgr.CreateCells(dataGridView1);
dgr.Cells[0].Value = pathOnly;
dgr.Cells[1].Value = fileNameOnly;
dataGridView1.Rows.Add(dgr);
filePath.Add(fileNames);
}
else
{
DataGridViewRow dgr2 = new DataGridViewRow();
dgr2.Cells[0].Value = "No Files To Clean Up";
dgr2.Cells[1].Value = "";
}
}
}
catch (Exception e)
{
StreamWriter sw = new StreamWriter(retPath + "ErrorLog.txt");
sw.Write(e);
}
}
private void button1_Click(object sender, EventArgs e)
{
//What do i type in here to call my FileCleanUp method???
}
}
SanitizeFileNames.cs code:
namespace FileMigration2
{
public class SanitizeFileNames
{
public static void FileCleanup(List<string>filePath)
{
string regPattern = "*[\\~#%&*{}/<>?|\"-]+*";
string replacement = "";
Regex regExPattern = new Regex(regPattern);
foreach (string files2 in filePath)
{
try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
//write to streamwriter
System.IO.File.Move(files2, sanitized);
}
catch (Exception ex)
{
//write to streamwriter
}
}
}
}
}
}
Any help is appreciated!
Thanks :)
Put
public partial class DriveRecursion_Results : Form {
List<string> filePath;
and in driveRecursion method, just use
filePath = new List<string>();
and in the action button method, why don't you do
if(filePath != null)
SanitizeFileNames.FileCleanup(filePath);
You call filePath.Add twice ?
Your 'else' is in the wrong place too.
What is dgr2?