Drag and drop a path in a wpf - c#

Is it possible to drag and drop a path in a wpf using Mouse Eventhandlers? In partcular I want to drag a path with the left mouse button and to mouse it on the grid. How can this be done?

Try this:
Given:
TextBox name is "TextBox1"
public MainWindow()
{
// Initialize UI
InitializeComponent();
// Loaded event
this.Loaded += delegate
{
TextBox1.AllowDrop = true;
TextBox1.PreviewDragEnter += TextBox1PreviewDragEnter;
TextBox1.PreviewDragOver += TextBox1PreviewDragOver;
TextBox1.Drop += TextBox1DragDrop;
};
}
/// <summary>
/// We have to override this to allow drop functionality.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void TextBox1PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
/// <summary>
/// Evaluates the Data and performs the DragDropEffect
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TextBox1PreviewDragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effects = DragDropEffects.Copy;
}
else
{
e.Effects = DragDropEffects.None;
}
}
/// <summary>
/// The drop activity on the textbox.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TextBox1DragDrop(object sender, DragEventArgs e)
{
// Get data object
var dataObject = e.Data as DataObject;
// Check for file list
if (dataObject.ContainsFileDropList())
{
// Clear values
TextBox1.Text = string.Empty;
// Process file names
StringCollection fileNames = dataObject.GetFileDropList();
StringBuilder bd = new StringBuilder();
foreach (var fileName in fileNames)
{
bd.Append(fileName + "\n");
}
// Set text
TextBox1.Text = bd.ToString();
}
}

Related

C# How to Save and load back listbox in form1_closing/open?

I'm wondering how could I save the info I have in my listbox and create one text file with that info and retrieve that information back to the listbox when form1 opens in the next session?
I have tried this but it didnt work.
private void Form1_Closing(object sender, EventArgs e)
{
Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
}
void Application_ApplicationExit(object sender, EventArgs e)
{
Properties.Settings.Default.Save();
}
You can use the XML serializer to save the list in XML format
/// <summary>
/// Writes the collection to the specified Xml file
/// </summary>
/// <typeparam name="T">type of the object which collection contains</typeparam>
/// <param name="objectToSave"></param>
/// <param name="path">xml file path</param>
public static void WriteXml<T>(this ICollection<T> objectToSave, string path) where T : class
{
// create an Xml Writer
var writer = new System.Xml.Serialization.XmlSerializer(objectToSave.GetType());
System.IO.StreamWriter file = new System.IO.StreamWriter(path);
// Serialize the data
writer.Serialize(file, objectToSave);
// close the file
file.Close();
}
public static ICollection<T> ReadXml<T>(this ICollection<T> objectToUse, string path) where T : class
{
try
{
// create the reader
var reader = new System.Xml.Serialization.XmlSerializer(objectToUse.GetType());
System.IO.StreamReader file = new System.IO.StreamReader(path);
// Deserialize the data
var data = reader.Deserialize(file);
file.Close();
if (data != null)
return data as ICollection<T>;
}
catch (FileNotFoundException)
{
}
return objectToUse;
}
Something like this:
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists("c:\\temp\\myfile.txt"))
{
var txtLines = File.ReadAllLines("c:\\temp\\myfile.txt");
listBox1.Items.AddRange(txtLines);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
var sb = new StringBuilder();
foreach (var i in listBox1.Items)
{
sb.AppendLine(i.ToString());
}
File.WriteAllText("c:\\temp\\myfile.txt", sb.ToString());
}

GridView lost search result after change page size or click on paging?

I have a gridview to show the data and and text box to do the search. When i search, the gridview could show the data correctly, but when I click on change page size or go to next page, the gridview will reload to the original state. Is there anything to do with the ViewState? Appreciate is someone could help. following is my code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
// handle event
DropDownList ddpagesize = sender as DropDownList;
GridView1.PageSize = Convert.ToInt32(ddpagesize.SelectedItem.Text);
ViewState["PageSize"] = ddpagesize.SelectedItem.Text;
GridView1.DataBind();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataSource1.SelectCommand = "" + txtSearchValue.Text + "'";
GridView1.DataBind();
}
protected void btnReload_Click(object sender, EventArgs e)
{
txtSearchValue.Text = "";
lblSearchError.Text = "";
GridView1.DataBind();
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Attributes["onmouseover"] =
"this.style.backgroundColor;this.style.backgroundColor='#AED4EB';";
row.Attributes["onmouseout"] =
"this.style.textDecoration='none';this.style.background='#ffffff';";
// Set the last parameter to True
// to register for event validation.
row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink(GridView1,
"Select$" + row.DataItemIndex, true);
}
}
base.Render(writer);
}
protected void btnDate_Click(object sender, EventArgs e)
{
SqlDataSource1.SelectCommand = "";
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int rowindex = GridView1.SelectedIndex % GridView1.PageSize;
GridViewRow row = GridView1.Rows[rowindex];
Session["TSO"] = row.Cells[7].Text.Trim();
string url = "http://localhost:60918/Requests.aspx";
StringBuilder sb = new StringBuilder();
sb.AppendLine("<script type='text/javascript'>");
sb.AppendLine("window.open('" + url + "')");
sb.AppendLine("<" + "/script>");
ScriptManager.RegisterStartupScript(upGrdCustomers, upGrdCustomers.GetType(), "myjs", sb.ToString(), false);
}
catch (System.Threading.ThreadAbortException)
{
throw;
}
}
Here is my code for the GridView:
[ToolboxData("<{0}:GridView runat=server></{0}:GridView>")]
public class GridView : System.Web.UI.WebControls.GridView, IPageableItemContainer
{
/// <summary>
/// TotalRowCountAvailable event key
/// </summary>
private static readonly object EventTotalRowCountAvailable = new object();
/// <summary>
///
/// </summary>
/// <param name="dataSource"></param>
/// <param name="dataBinding"></param>
/// <returns></returns>
protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
{
int rows = base.CreateChildControls(dataSource, dataBinding);
// if the paging feature is enabled, determine
// the total number of rows in the datasource
if (this.AllowPaging)
{
// if we are databinding, use the number of rows that were created,
// otherwise cast the datasource to an Collection and use that as the count
int totalRowCount = dataBinding ? rows : ((ICollection)dataSource).Count;
// raise the row count available event
IPageableItemContainer pageableItemContainer = this as IPageableItemContainer;
this.OnTotalRowCountAvailable(
new PageEventArgs(
pageableItemContainer.StartRowIndex,
pageableItemContainer.MaximumRows,
totalRowCount
)
);
// make sure the top and bottom pager rows are not visible
if (this.TopPagerRow != null)
{
this.TopPagerRow.Visible = false;
}
}
return rows;
}
#region IPageableItemContainer Interface
/// <summary>
///
/// </summary>
/// <param name="startRowIndex"></param>
/// <param name="maximumRows"></param>
/// <param name="databind"></param>
void IPageableItemContainer.SetPageProperties(
int startRowIndex, int maximumRows, bool databind)
{
int newPageIndex = (startRowIndex / maximumRows);
this.PageSize = maximumRows;
if (this.PageIndex != newPageIndex)
{
bool isCanceled = false;
if (databind)
{
// create the event args and raise the event
GridViewPageEventArgs args = new GridViewPageEventArgs(newPageIndex);
this.OnPageIndexChanging(args);
isCanceled = args.Cancel;
newPageIndex = args.NewPageIndex;
}
// if the event wasn't cancelled
// go ahead and change the paging values
if (!isCanceled)
{
this.PageIndex = newPageIndex;
if (databind)
{
this.OnPageIndexChanged(EventArgs.Empty);
}
}
if (databind)
{
this.RequiresDataBinding = true;
}
}
}
/// <summary>
///
/// </summary>
int IPageableItemContainer.StartRowIndex
{
get { return this.PageSize * this.PageIndex; }
}
/// <summary>
///
/// </summary>
int IPageableItemContainer.MaximumRows
{
get { return this.PageSize; }
}
/// <summary>
///
/// </summary>
event EventHandler<PageEventArgs> IPageableItemContainer.TotalRowCountAvailable
{
add { base.Events.AddHandler(GridView.EventTotalRowCountAvailable, value); }
remove { base.Events.RemoveHandler(GridView.EventTotalRowCountAvailable, value); }
}
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected virtual void OnTotalRowCountAvailable(PageEventArgs e)
{
EventHandler<PageEventArgs> handler = (EventHandler<PageEventArgs>)base.Events[GridView.EventTotalRowCountAvailable];
if (handler != null)
{
handler(this, e);
}
}
#endregion
}
}
In your server side event handler called ddPageSize_SelectedIndexChanged you are calling Databind on your grid without checking if there is a search term entered and setting that on the DataSource of the Grid.
protected void ddPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
...
SqlDataSource1.SelectCommand = "" + txtSearchValue.Text + "'";
GridView1.DataBind();
}
Try this. When you change the pagesize it triggers a postback and leaving the value for SelectCommand as empty resulting the gridview to load in it's original state. Set it to txtSearchValue.Text and try
protected void ddPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
// handle event
DropDownList ddpagesize = sender as DropDownList;
GridView1.PageSize = Convert.ToInt32(ddpagesize.SelectedItem.Text);
ViewState["PageSize"] = ddpagesize.SelectedItem.Text;
SqlDataSource1.SelectCommand = "" + txtSearchValue.Text + "'";
GridView1.DataBind();
}

How can I keep all the focused forms?

I've an application that use two forms: Form1 (main) and Form2 (secondary). I show the Form2 with the following code:
Form2 frm = new Form2();
frm.TopMost = true;
frm.Show();
When the Form2 is visible, it hasn't the focus. How can I do the focus at the Form2 and keep the focus at the Form1? Sorry for my bad english!
try bellow code within MDI Parent Form (Main Form)
private Form2 _form2;
#region UtilOpenForm
/// <summary>
/// UtilOpenForm
/// </summary>
/// <param name="appContainer"></param>
/// <param name="childForm"></param>
private void UtilOpenForm(Form appContainer, Form childForm)
{
this.Cursor = Cursors.WaitCursor;
if (childForm == null)
{
throw new ArgumentNullException("childForm");
}
childForm.MdiParent = appContainer;
childForm.StartPosition = FormStartPosition.CenterScreen;
childForm.MaximizeBox = false;
childForm.MinimizeBox = false;
childForm.Closed += new EventHandler(childForm_Closed);
childForm.Show();
this.Cursor = Cursors.Default;
}
Now from Button / Menu click within MDI Parent
if (_form2 == null)
{
UtilOpenForm(this, _form2 = new Form2());
}
Now child form close Function within MDI Parent
#region childForm_Closed
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void childForm_Closed(object sender, EventArgs e)
{
if (sender.GetType() == typeof(Form2))
{
_form2.Dispose();
if (_form2 != null)
{
_form2 = null;
}
}

BackgroundWorker - Report Time

I have a control on my GUI which I would like to make visible only case when I run BackgroundWorkers (many different operations). Some of these operations last less than 500ms, and I feel that making the control visible for so short a time is useless. Therefore, I would like to make the control visible only if a BackgroundWorker has already been working for 500ms.
Just start a timer at the same time you start the BGW:
private void button1_Click(object sender, EventArgs e) {
timer1.Enabled = true;
backgroundWorker1.RunWorkerAsync();
}
private void timer1_Tick(object sender, EventArgs e) {
timer1.Enabled = false;
myControl1.Visible = true;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
timer1.Enabled = myControl1.Visible = false;
}
Leverage the ReportProgress method on the BackgroundWorker. You can place whatever you want in the state parameter and then perform the calculation accordingly.
public class MyObject
{
public DateTime TimeStarted {get; set;}
}
Then in your ProgressChanged event handler...
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if(DateTime.Now.Subtract(((MyObject)e.UserState).TimeStarted).TotalMilliseconds > 500)
{
//show your control
}
}
You can use a Timer inside the BackgroundWorker and call the ReportProgress method once 500ms have passed.
In the UI thread you then just need to handle the ProgressChanged event and show/hide your control as required.
public partial class Form1 : Form
{
/// <summary>
/// Timer.
/// </summary>
private Timer timer = new Timer();
/// <summary>
/// Initializes a new instance of the <see cref="Form1"/> class.
/// </summary>
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += BackgroundWorker1DoWork;
backgroundWorker1.ProgressChanged += BackgroundWorker1ProgressChanged;
timer.Interval = 500;
timer.Tick += TimerTick;
}
/// <summary>
/// Handles the Tick event of the timer control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void TimerTick(object sender, EventArgs e)
{
timer.Enabled = false;
backgroundWorker1.ReportProgress(99);
}
/// <summary>
/// Handles the Click event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void Button1Click(object sender, EventArgs e)
{
timer.Enabled = true;
backgroundWorker1.RunWorkerAsync();
}
/// <summary>
/// Handles the DoWork event of the backgroundWorker1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param>
private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
// Do your work...
Thread.Sleep(2000);
}
/// <summary>
/// Handles the ProgressChanged event of the backgroundWorker1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.ProgressChangedEventArgs"/> instance containing the event data.</param>
private void BackgroundWorker1ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Visible = (e.ProgressPercentage == 99);
}
}

How to fetch or grab input from my forms app

I'm randomperson heres my code and it is a calculator:
namespace WindowsFormsApplication1
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.num1 = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.num1)).BeginInit();
this.SuspendLayout();
//
// num1
//
this.num1.AccessibleName = "";
this.num1.Location = new System.Drawing.Point(12, 12);
this.num1.Name = "num1";
this.num1.Size = new System.Drawing.Size(120, 20);
this.num1.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.num1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.num1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.NumericUpDown num1;
}
}
There is only a NumericUpDown control in your form so i'm assuming you want to fetch that value of that control. You'll have to use num1.Value to get it's value.
Try
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
num1.ValueChanged += new EventHandler(numericUpDown1_ValueChanged);
}
void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
MessageBox.Show("New value : " +num1.Value);
}

Categories