How to pass an argument to new RoutedEventHandler method in C#? - c#

I am trying to make an application launcher and in the end i am trying to pass and extra argument to RoutedEventHandler method call but its giving me an error, i tried looking it up on google but i didn't understand a damn thing. (i am noob) so here is the code please have a look and it.Thanks
namespace Button_Launcher
{
public partial class MainWindow : Window
{
private string line;
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog fileName = new OpenFileDialog();
fileName.Filter = "executables (.exe)|*.exe";
fileName.ShowDialog();
StreamWriter writer = new StreamWriter("E:/Config.txt",true);
writer.WriteLine(fileName.FileName);
writer.Close();
textBox.Text = fileName.FileName;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
string file = ("E:/Config.txt");
StreamReader Reader = new StreamReader(file, Encoding.ASCII);
List<string> appList = new List<string>();
List<string> Items = new List<string>();
int count = 1;
while ((line = Reader.ReadLine()) != null)
{
makeButton(line,count);
count++;
}
Reader.Close();
}
public void makeButton(string link,int count)
{
string[] mySplit = link.Split(new char[] { '\\' });
string[] name = mySplit.Last().Split(new char[] { '.' });
string fName = name.First();
string buttonName = fName;
Button newBtn = new Button();
newBtn.Content = buttonName;
newBtn.Height = 30;
newBtn.Width = 70;
newBtn.Margin = new Thickness(-60, 90*count/1.5, 180,80);
StackPanel sp = new StackPanel();
sp.Children.Add(newBtn);
mainGrid.Children.Add(sp);
newBtn.Click += new RoutedEventHandler(launchApp(link));
//launchApp(link);
}
private void launchApp(string link,object sender, RoutedEventArgs e)
{
Process.Start(link);
}
}
}

You cannot change the method signature of the RoutedEventHandler. Instead, try storing the link data in the Tag property of your button. Then in the method you could cast the sender object to a button and access the tag property.
public void makeButton(string link,int count)
{
string[] mySplit = link.Split(new char[] { '\\' });
string[] name = mySplit.Last().Split(new char[] { '.' });
string fName = name.First();
string buttonName = fName;
Button newBtn = new Button();
newBtn.Content = buttonName;
newBtn.Height = 30;
newBtn.Width = 70;
newBtn.Tag = link;
newBtn.Margin = new Thickness(-60, 90*count/1.5, 180,80);
StackPanel sp = new StackPanel();
sp.Children.Add(newBtn);
mainGrid.Children.Add(sp);
newBtn.Click += launchApp;
//launchApp(link);
}
private void launchApp(object sender, RoutedEventArgs e)
{
var btn = sender as Button;
if( btn == null )
return;
Process.Start(btn.Tag.ToString( ));
}

Related

Dynamic controls dissapearing on postback

I am creating dynamic textboxes when clicking on a set of different radio button. Below is an example of two radio button onclick event.
protected void Checkbox1_CheckedChanged(object sender, EventArgs e)
{
string servicename = "service1";
if (checkbox1.Checked)
{
InputParameters.InputParameters aa= new InputParameters.InputParameters();
textbox = aa.GetInputFields(servicename);
for (int i=0;i<textbox.Count;i++)
{
// declare a textbox
TextBox CPDT = new TextBox();
CPDT.ID = servicename + i.ToString();
CPDT.CssClass = "form-control";
CPDT.EnableViewState = true;
Label lblCPD=new Label();
lblCPD.ID = "txtDynamiclbl" + servicename+ i.ToString();
lblCPD.CssClass= "form-control-label";
lblCPD.Text= textbox[i].ToString();
lblCPD.EnableViewState = true;
CPDPlaceHolder.Controls.Add(lblCPD);
CPDPlaceHolder.Controls.Add(CPDT);
//this.NumberOfControls++;
}
Button callSoap = new Button();
callSoap.ID = "txtDynamicSearch" + servicename;
callSoap.Text = "Search";
callSoap.CssClass = ".btn-info";
callSoap.CommandArgument = "test";
callSoap.Click += new EventHandler(btnsoap);
callSoap.EnableViewState = true;
CPDPlaceHolder.Controls.Add(callSoap);
}
else
{
}
}
protected void Checkbox2_CheckedChanged(object sender, EventArgs e)
{
string servicename = "service2";
if (checkbox2.Checked)
{
InputParameters.InputParameters aa = new InputParameters.InputParameters();
List<String> textbox = aa.GetInputFields("test1");
// textboxs.AddRange(textbox);
for (int i = 0; i < textbox.Count; i++)
{
// declare a textbox
TextBox CPDT = new TextBox();
CPDT.ID = servicename + i.ToString();
CPDT.CssClass = "form-control";
Label lblCPD = new Label();
lblCPD.ID = "txtDynamiclbl" + servicename + i.ToString();
lblCPD.CssClass = "form-control-label";
lblCPD.Text = textbox[i].ToString();
CPDPlaceHolder.Controls.Add(lblCPD);
CPDPlaceHolder.Controls.Add(CPDT);
}
Button callSoap = new Button();
callSoap.ID = "txtDynamicSearch" + servicename;
callSoap.Text = "Search";
callSoap.CssClass = ".btn-info";
callSoap.CommandArgument = "test1";
callSoap.Click += new EventHandler(btnsoap);
callSoap.EnableViewState = true;
CPDPlaceHolder.Controls.Add(callSoap);
}
else
{
}
}
The textboxes and search button appears as needed. The problem now is when i clicked on the search button a post back occur and all the controls are gone. I have been reading a lot about initialising the controls in page_preinit and i tried the code below.
protected void Page_PreInit(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
try
{
foreach (string key in keys)
{
TextBox CPDT = new TextBox();
CPDT.ID = "test" + i.ToString();
CPDT.CssClass = "form-control";
Label lblCPD = new Label();
lblCPD.ID = "txtDynamiclbl" + "test" + i.ToString();
lblCPD.CssClass = "form-control-label";
lblCPD.Text = textbox[i].ToString();
CPDPlaceHolder.Controls.Add(lblCPD);
CPDPlaceHolder.Controls.Add(CPDT);
i++;
}
}
catch
{
}
}
In the above function this line only returns the search button and not the texboxes. I am stuck on this issue.
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
T

TweetInvi Listview can't get TweetID

I'm trying to get Tweet ID via TweetInvi API but always get null point exception. I'm out of options and can't understand what i did wrong. Here is my code. Problem occurs when i select desired Item from view and press retweet.
namespace MIF_TwitterApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Auth.SetUserCredentials("KEY", "KEY", "KEY",
"KEY");
}
private void Form1_Load(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
//PROFILE
profileImage.ImageLocation = user.ProfileImageUrlFullSize;
nameLabel.Text = user.Name;
usernameLabel.Text = "#" + user.ScreenName;
followersLabel.Text = "Followers: " + user.FollowersCount;
}
//Tweeting with PICS
private void tweetBtn_Click(object sender, EventArgs e)
{
if (tweetBox.Text != "")
{
if (imgUploadPath.Text != "")
{
byte[] file = File.ReadAllBytes(imgPreview.ImageLocation);
Tweet.PublishTweetWithImage(tweetBox.Text, file);
imgPreview.ImageLocation = "";
imgUploadPath.Text = "";
tweetBox.Clear();
MessageBox.Show("Tweet posted!");
}
else
{
Tweet.PublishTweet(tweetBox.Text);
MessageBox.Show("Tweet posted!");
tweetBox.Clear();
}
}
else
{
MessageBox.Show("Please enter text!");
tweetBox.Clear();
}
}
private void addImg_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
imgPreview.ImageLocation = ofd.FileName;
imgUploadPath.Text = ofd.FileName;
}
private void dropImg_Click(object sender, EventArgs e)
{
imgPreview.ImageLocation = "";
imgUploadPath.Text = "";
}
private void timelineBtn_Click(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
var getTweets = Timeline.GetHomeTimeline(40);
listView1.Clear();
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Tweet", 570);
listView1.Columns.Add("Created By", 130);
listView1.Columns.Add("Create Time", 130);
listView1.Columns.Add("Likes", 60);
listView1.Columns.Add("Retweets", 70);
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
}
}
private void postsBtn_Click(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
var getTweets = Timeline.GetUserTimeline(user, 40);
listView1.Clear();
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Tweet", 570);
listView1.Columns.Add("Created By", 130);
listView1.Columns.Add("Create Time", 130);
listView1.Columns.Add("Likes", 60);
listView1.Columns.Add("Retweets", 70);
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
}
}
private void retweetBtn_Click(object sender, EventArgs e)
{
var checkedItems = listView1.SelectedItems;
long a = (long)listView1.SelectedItems[0].Tag;
var user = User.GetAuthenticatedUser();
var retweet = Tweet.PublishRetweet(a);
MessageBox.Show("Retweet was successfull");
listView1.Items.Clear();
}
}
}
Breakes on long a, I can't figure out how to get that Long Tweet ID
Here is the full code
Problem was that my X was not incrementing correctly as it was out of for loop.
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
x = x +1;
}

how to add event reminder to my windows phone 7 application

I am building an app in windows phone 7 where i need to add an event reminder. On clicking a button the reminder should be set. My cs file is:
namespace KejriwalPhoneApp
{
public partial class EventDetails : PhoneApplicationPage
{
public EventDetails()
{
InitializeComponent();
ApplicationBar = new ApplicationBar();
ApplicationBar.Mode = ApplicationBarMode.Default;
ApplicationBar.Opacity = 1.0;
ApplicationBar.IsVisible = true;
ApplicationBarIconButton home = new ApplicationBarIconButton();
home.IconUri = new Uri("/Image/icon_home_deselect.png", UriKind.Relative);
home.Text = "Home";
ApplicationBar.Buttons.Add(home);
home.Click += new EventHandler(home_Click);
ApplicationBarIconButton share = new ApplicationBarIconButton();
share.IconUri = new Uri("/Image/icon_share_deselect.png", UriKind.Relative);
share.Text = "Share";
ApplicationBar.Buttons.Add(share);
share.Click += new EventHandler(share_Click);
ApplicationBarIconButton news = new ApplicationBarIconButton();
news.IconUri = new Uri("Image/icon_news_deselect.png", UriKind.Relative);
news.Text = "News";
ApplicationBar.Buttons.Add(news);
news.Click += new EventHandler(news_Click);
ApplicationBarIconButton events = new ApplicationBarIconButton();
events.IconUri = new Uri("/Image/icon_event_deselect.png", UriKind.Relative);
events.Text = "Video";
ApplicationBar.Buttons.Add(events);
events.Click += new EventHandler(events_Click);
}
void events_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/Events.xaml", UriKind.Relative));
}
void news_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/News.xaml", UriKind.Relative));
}
void share_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/share.xaml", UriKind.Relative));
}
void home_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
private void Image_Back(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Events.xaml", UriKind.Relative));
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var imagePath = "";
var eventdate = "";
var location = "";
var utimee = "";
var tzone = "";
var ename = "";
var desc = "";
//check if particular parameter available in uri string
if (this.NavigationContext.QueryString.ContainsKey("image_path"))
{
//if it is available, get parameter value
imagePath = NavigationContext.QueryString["image_path"];
eventimage.Source = new BitmapImage(new Uri(#"http://political-leader.vzons.com/ArvindKejriwal/images/uploaded/" + imagePath, UriKind.Absolute));
}
if (this.NavigationContext.QueryString.ContainsKey("Time_Zone"))
{
tzone = NavigationContext.QueryString["Time_Zone"];
timezone.Text = tzone;
}
if (this.NavigationContext.QueryString.ContainsKey("uTime"))
{
utimee = NavigationContext.QueryString["uTime"];
utime.Text = utimee;
}
if (this.NavigationContext.QueryString.ContainsKey("Event_Date"))
{
//if it is available, get parameter value
eventdate = NavigationContext.QueryString["Event_Date"];
evntdate.Text = eventdate;
}
if (this.NavigationContext.QueryString.ContainsKey("Location"))
{
//if it is available, get parameter value
location = NavigationContext.QueryString["Location"];
loc.Text = location;
}
if (this.NavigationContext.QueryString.ContainsKey("Event_Name"))
{
//if it is available, get parameter value
ename = NavigationContext.QueryString["Event_Name"];
enamee.Text = ename;
}
if (this.NavigationContext.QueryString.ContainsKey("Event_Description"))
{
//if it is available, get parameter value
desc = NavigationContext.QueryString["Event_Description"];
edescription.Text = desc;
}
}
private void Image_Previous(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Events.xaml", UriKind.Relative));
}
private void Image_rem(object sender, RoutedEventArgs e)
{
RegisterReminder();
}
private void RegisterReminder()
{
var reminder = ScheduledActionService.Find(ename) as Reminder ?? new Reminder(ename);
reminder.Title = ename;
reminder.Content = desc;
// parse eventDate,utimee to beginDateTime
reminder.BeginTime = beginDateTime;
reminder.ExpirationTime = reminder.BeginTime.AddDays(1);
reminder.RecurrenceType = RecurrenceInterval.None;
if (ScheduledActionService.Find(ename) == null)
ScheduledActionService.Add(reminder);
else
ScheduledActionService.Replace(reminder);
MessageBox.Show("reminder set succeed!");
}
}
}Now when the reminder button is clicked i want the fields utimee, tzone to be set and i get a pop up message "Event reminder added successfully"
I am not getting the idea on how to do this
You can do these steps:
1.get the values from webservice as global variableļ¼š
eventDate,location, utimee, tzone, ename,desc.
2.click the reminder button, execute the click method
private void BtnReminderClick(object sender, EventArgs e)
{
RegisterReminder();
}
3.do reminder register
private void RegisterReminder()
{
var reminder = ScheduledActionService.Find(ename) as Reminder ?? new Reminder(ename);
reminder.Title = ename;
reminder.Content = desc;
// parse eventDate,utimee to beginDateTime
reminder.BeginTime = DateTime.Parse(eventDate).Date + DateTime.Parse(utimee).TimeOfDay;
reminder.ExpirationTime = reminder.BeginTime.AddDays(1);
reminder.RecurrenceType = RecurrenceInterval.None;
if (ScheduledActionService.Find(ename) == null)
ScheduledActionService.Add(reminder);
else
ScheduledActionService.Replace(reminder);
MessageBox.Show("reminder set succeed!");
}

C# class to play a video file

I have this class,
public class ImageBox : Grid
{
Image imgclose; public String path;
List<ImageBox> ImageBoxes;
public ImageBox(string label,List<ImageBox> ImBox)
{
this.ImageBoxes = ImBox;
imgclose = new Image();
imgclose.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("pack://application:,,,/Close.ico"));
imgclose.Width = 20; imgclose.Height = 20; imgclose.Cursor = Cursors.Hand; imgclose.HorizontalAlignment = System.Windows.HorizontalAlignment.Right; imgclose.VerticalAlignment = System.Windows.VerticalAlignment.Top;
imgclose.Visibility = System.Windows.Visibility.Hidden;
imgclose.MouseLeftButtonDown += new MouseButtonEventHandler(imgclose_MouseLeftButtonDown);
this.MouseEnter += new MouseEventHandler(Blank_MouseEnter);
this.MouseLeave += new MouseEventHandler(Blank_MouseLeave);
this.Height = 100; this.Width = 100;
try
{
System.Windows.Forms.OpenFileDialog open = new System.Windows.Forms.OpenFileDialog();
path = open.FileName.Replace(Directory.GetCurrentDirectory(), "");
this.Background = new System.Windows.Media.ImageBrush(new System.Windows.Media.Imaging.BitmapImage(new Uri(label)));
path = label;
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
Grid.SetColumn(imgclose, 0); Grid.SetRow(imgclose, 1);
this.Children.Add(imgclose);
ContextMenu contextMenu1 = new ContextMenu();
MenuItem conitem1 = new MenuItem() { Header = "Send to back" }; conitem1.Click += new System.Windows.RoutedEventHandler(conitem1_Click);
MenuItem conitem2 = new MenuItem() { Header = "Bring to Front" }; conitem2.Click += new System.Windows.RoutedEventHandler(conitem2_Click);
contextMenu1.Items.Add(conitem1); contextMenu1.Items.Add(conitem2);
this.ContextMenu = contextMenu1;
}
void conitem1_Click(object sender, EventArgs e)
{
Canvas.SetZIndex(this, (Canvas.GetZIndex(this) - 1));
}
void conitem2_Click(object sender, EventArgs e)
{
Canvas.SetZIndex(this, (Canvas.GetZIndex(this) + 1));
}
void Blank_MouseEnter(object sender, MouseEventArgs e)
{
imgclose.Visibility = System.Windows.Visibility.Visible;
}
void Blank_MouseLeave(object sender, MouseEventArgs e)
{
imgclose.Visibility = System.Windows.Visibility.Hidden;
}
void imgclose_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (System.Windows.MessageBox.Show("Are you sure?", "Confirm", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Question) == System.Windows.MessageBoxResult.OK)
{
ImageBoxes.Remove(this);
(this.Parent as System.Windows.Controls.Canvas).Children.Remove(this);
}
else
{
}
}
}
This class displays an image (chosen from a dialog box).
How can I modify it to make it play a video file ?
More precisely,
How should I modify the line
this.Background = new System.Windows.Media.ImageBrush(new System.Windows.Media.Imaging.BitmapImage(new Uri(label)));
path = label;
so that it plays a video file.
The Background property has to have some sort of Brush in it. A quick Google search came up with this: VideoBrush. I hope this is what you were looking for.

When a combobox is chosen a openFileDialog must appear

I have made a method so that when you click on Browse From File the openDialogBox appear. But it does not . What is wrong ?
This is the method that I made to Open the OpenFileDialog:
public void Lista()
{
string[] col2 = new string[dataGridView1.Rows.Count];
for (int i = 0; i < dataGridView1.Rows.Count; i++)
if (col2[i] == "Browse From File...")
{
DialogResult result2 = openFileDialog2.ShowDialog();
if (result2 == DialogResult.OK)
{
// filename = openFileDialog1.FileName;
}
}
}
This is the method where I call the method Lista.
private void button1_Click(object sender, EventArgs e)
{
// opens window **BROWSE**
openFileDialog1.Title = "Choose File CSV ";
string filename = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog1.FileName;
textBox1.Text = filename;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(textBox1.Text);
stringforData = file.ReadLine();
while ((line = file.ReadLine()) != null)
{
//read inside the table
fileList.Add(line.Split(';'));
}
file.Close();
this.ToDataGrid();
this.Lista();
}
}
DataGridView by only having one editing control for all the rows. Here's how I handled a similar situation, First try a delegate to the EditControlShowing event
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OpenFileDialog ofd = new OpenFileDialog();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("ID", "Product ID");
DataGridViewComboBoxColumn comboxboxCol = new DataGridViewComboBoxColumn();
comboxboxCol.HeaderText = "Type";
comboxboxCol.Items.Add("Obj1");
comboxboxCol.Items.Add("Obj2");
comboxboxCol.Items.Add("Obj3");
dataGridView1.Columns.Add(comboxboxCol);
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(Grid_EditingControlShowing);
}
void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
// the event to handle combo changes
EventHandler comboDelegate = new EventHandler(
(cbSender, args) =>
{
ofd.ShowDialog();
});
// register the event with the editing control
combo.SelectedValueChanged += comboDelegate;
}
}
}
}
Hope this will solve your Issue

Categories