C# Pass variables from a dynamically created event - c#

My problem is this: I have a form which is created at runtime within it's own function which takes 2 parameters to retrieve a text value from a dataGridView and display it in a textBox. The issue is that when I call this function on it's own it works fine however when called from another runtime-created form control event, no text value is returned but the form is still displayed. This is the code which creates and shows the form:
private void commentsForm(int x, int y)
{
using (Form frmDisplayText = new Form())
{
TextBox txt = new TextBox();// <- Decleration
Button btnAccept = new Button();
Button btnRevert = new Button();
Button btnClose = new Button();
frmDisplayText.Size = new Size(550, 350);// <- Size
txt.Size = new Size(510, 250);
btnAccept.Size = new Size(216, 30);
btnRevert.Size = new Size(216, 30);
btnClose.Size = new Size(66, 30);
txt.Location = new Point(12, 12);// <- Location
btnAccept.Location = new Point(12, 269);
btnRevert.Location = new Point(234, 269);
btnClose.Location = new Point(456, 269);
string dataToOutput = dataGridView1.Rows[x].Cells[y].Value.ToString();// <- Text
txt.Text = dataToOutput;
frmDisplayText.Text = "Comments";
btnAccept.Text = "Accept";
btnRevert.Text = "Revert";
btnClose.Text = "Cancel";
txt.Multiline = true;// <- Other
btnAccept.Font = new Font(FontFamily.GenericSansSerif, 12.0F, FontStyle.Regular);
btnRevert.Font = new Font(FontFamily.GenericSansSerif, 12.0F, FontStyle.Regular);
btnClose.Font = new Font(FontFamily.GenericSansSerif, 12.0F, FontStyle.Regular);
btnAccept.Click += (_, args) =>// <- Event Handlers
{
string txtText = txt.Text;
using (var conn = new SqlConnection(connection))
{
string SQL = "UPDATE Comments SET [" + dataGridView1.Rows[x].Cells[y].OwningColumn.HeaderText.ToString() + "] = #val2 WHERE ID = #val3";
using (var cmd = new SqlCommand(SQL, conn))
{
cmd.Parameters.AddWithValue("#val2", txt.Text);
cmd.Parameters.AddWithValue("#val3", dataGridView1.Rows[x].Cells[0].Value.ToString());
try
{
conn.Open();
cmd.ExecuteNonQuery();
dataGridView1.Rows[x].Cells[y].Value = txt.Text;
MessageBox.Show("Success");
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
};
btnRevert.Click += (_, args) =>
{
txt.Text = dataToOutput;
};
btnClose.Click += (_, args) =>
{
frmDisplayText.Close();
};
frmDisplayText.Controls.Add(txt);// <- Add Controls
frmDisplayText.Controls.Add(btnAccept);
frmDisplayText.Controls.Add(btnRevert);
frmDisplayText.Controls.Add(btnClose);
frmDisplayText.ShowDialog();
}
}
And here is when it is called:
btnAddComment.Click += (_, args) =>
{
commentsForm(x, y);
};
Any ideas as to why the text property is null when called form here?
Thanks all

There is an addition to the row index which was throwing off the data to retrieve.

Related

How to display the defined amount of textboxes dynamically in separate class for few forms?

I have SQLite database wherein there is a table with some quantity of rows. I have a task to display the same quantity of textboxes in few forms with taking into account the coordinates of these controls. The names of these textboxes should be taken from one of the columns of this table. Also the labels must be present. Their names should be similar. Taking into account the fact the values of this column of this table is cyrillic I have decided to translate it into latinic symbols in the class Decryptor.
I've found the solution to perform the focus of displaying necessary textboxes in one form and I am able to copy this code into other forms. But it isn't good idea it seems despite the fact it would work in this case.
I've created new class - CommunicationCanalsDrawing. The idea of this class is reduction of code quantity and incresing of the usage convinience of this code. My code of particular class:
class CommunicationCanalsDrawing
{
public int Tx { get; set; }
public int Ty { get; set; }
public int Lx { get; set; }
public int Ly { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string[] Labels;
private string[] Textboxes;
public TextBox txt = new TextBox();
public Label l = new Label();
public int i { get; set; }
public void DrawThat()
{
Ly += 32;
Ty += 32;
Decryptor decr = new Decryptor();
decr.Word = Labels[i];
Textboxes[i] = decr.Decrypt();
txt = new TextBox();
txt.Name = Textboxes[i];
txt.Text = "";
txt.Width = Width;
txt.Height = Height;
txt.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F,
System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point,
((byte)(204)));
txt.Location = new System.Drawing.Point(Tx, Ty);
l = new Label();
l.Name = "l_" + Textboxes[i];
l.Text = Labels[i];
l.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F,
System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point,
((byte)(204)));
l.Location = new System.Drawing.Point(Lx, Ly);
}
public void ListOfColumns()
{
SQLiteConnection m_dbConn = new SQLiteConnection();
SQLiteCommand m_sqlCmd = new SQLiteCommand();
int AmountTextbox = 0;
try
{
InceptDb cl = new InceptDb();
m_dbConn = new SQLiteConnection("Data Source=" +
cl.dbFileName + ";Version=3;");
m_dbConn.Open();
m_sqlCmd.Connection = m_dbConn;
m_sqlCmd.CommandText = "SELECT COUNT(*) FROM communication_remedies";
AmountTextbox = Convert.ToInt32(m_sqlCmd.ExecuteScalar().ToString());
}
catch (SQLiteException ex)
{
MessageBox.Show("Error count*: " + ex.Message);
}
m_dbConn.Close();
if (AmountTextbox == 0)
{
MessageBox.Show("Довідник каналів зв'язку пустий.");
Organizations o = new Organizations();
o.Close();
}
m_dbConn = new SQLiteConnection();
m_sqlCmd = new SQLiteCommand();
Labels = new string[AmountTextbox];
Textboxes = new string[AmountTextbox];
try
{
InceptDb cl = new InceptDb();
m_dbConn = new SQLiteConnection("Data Source=" +
cl.dbFileName + ";Version=3;");
m_dbConn.Open();
m_sqlCmd.Connection = m_dbConn;
m_sqlCmd.CommandText = "SELECT name FROM communication_remedies";
DataTable dt = new DataTable();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(m_sqlCmd.CommandText,
m_dbConn);
adapter.Fill(dt);
Labels =
dt.AsEnumerable().Select(r => r.Field<string>("name")).ToArray();
}
catch (SQLiteException ex)
{
MessageBox.Show("Error count*: " + ex.Message);
}
m_dbConn.Close();
}
}
My code of some form:
private void Organizations_Load(object sender, EventArgs e)
{
CommunicationCanalsDrawing comm = new CommunicationCanalsDrawing();
comm.ListOfColumns();
comm.Lx = 12;
comm.Tx = 243;
comm.Ty = 173;
comm.Ly = 207;
comm.Height = 26;
comm.Width = 228;
for (int i = 0; i < comm.Labels.Length; i++ )
{
comm.i = i;
comm.DrawThat();
this.Controls.Add(comm.txt);
this.Controls.Add(comm.l);
}
}
I know the coordinates of the controls can be incorrect, but it does not matter now. It's easy to rectify. I see only the last textbox and the last label. Others aren't displayed.
Your problem is you are creating only once instance of CommunicationCanalsDrawing and then doing your for loop on its properties. That way you end up with only the last. You need to create a new instance of CommunicationCanalsDrawing on each cycle through the for loop:
private void Organizations_Load(object sender, EventArgs e)
{
for (int i = 0; i < comm.Labels.Length; i++ )
{
CommunicationCanalsDrawing comm = new CommunicationCanalsDrawing();
comm.ListOfColumns();
comm.Lx = 12;
comm.Tx = 243;
comm.Ty = 173;
comm.Ly = 207;
comm.Height = 26;
comm.Width = 228;
comm.i = i;
comm.DrawThat();
this.Controls.Add(comm.txt);
this.Controls.Add(comm.l);
}
}

Refreshing of several controls in loop Winforms

I'm trying to make weather application. And when I input new city in my combobox,my labels and pictureboxes don't refresh. I have already tried Refresh() Update() and Invalidate() and none of them worked. Tell me please ,what I'm suppose to do. Thank you in advance!
private async void SetWeatherForecastDataToWeatherApp(string city)
{
try
{
var jsonData = string.Empty;
var url = string.Format("http://api.openweathermap.org/data/2.5/forecast?q={0}&APPID=a54961a05f7a1fc0cf9bd2bf1465dea5", city);
var uri = new Uri(url);
var request = WebRequest.Create(uri);
var response = await request.GetResponseAsync();
using (var stream = response.GetResponseStream())
{
using (var streamReader = new StreamReader(stream))
{
jsonData = await streamReader.ReadToEndAsync();
}
}
response.Close();
_jsonFutureWeatherForecastData = jsonData;
_weatherForecast = JsonConvert.DeserializeObject<WeatherForecast>(_jsonFutureWeatherForecastData);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Input Error", MessageBoxButtons.OK);
}
var dayNameLabelList = new List<Label>();
var weatherDescriptionLablList = new List<Label>();
var gradesLabel = new List<Label>();
var pictureBoxList = new List<PictureBox>();
int yLocation = 50;
int xLocation = Width / 2;
int cnt = 0;
string currDayOfWeek = string.Empty;
string CurrentDate = string.Empty;
for (int i = 0; i < 9; i++)
{
currDayOfWeek = _dateConverter.ConvertMilisecondsToCurrentTime(_weatherForecast.WeatherList[i].CurrentDate).DayOfWeek.ToString();
CurrentDate = _dateConverter.ConvertMilisecondsToCurrentTime(_weatherForecast.WeatherList[i].CurrentDate).Day.ToString();
cnt++;
pictureBoxList.Add(new PictureBox());
pictureBoxList[i].Name = "WeatherForecastImage" + cnt.ToString();
pictureBoxList[i].Location = new Point(xLocation, yLocation);
pictureBoxList[i].Load($"Icons/{_weatherForecast.WeatherList[i].Weather[0].Icon}.png");
Controls.Add(pictureBoxList[i]);
pictureBoxList[i].Invalidate();
dayNameLabelList.Add(new Label());
dayNameLabelList[i].Text = currDayOfWeek + " " + CurrentDate;
dayNameLabelList[i].Location = new Point(xLocation + 100, yLocation);
dayNameLabelList[i].Size = new Size(100, 15);
dayNameLabelList[i].Font = new Font("Lucida Sans", 10, FontStyle.Regular);
Controls.Add(dayNameLabelList[i]);
weatherDescriptionLablList.Add(new Label());
weatherDescriptionLablList[i].Text = _weatherForecast.WeatherList[i].Weather[0].Description;
weatherDescriptionLablList[i].Location = new Point(xLocation + 100, yLocation + 15);
weatherDescriptionLablList[i].Font = new Font("Lucida Sans", 8, FontStyle.Regular);
Controls.Add(weatherDescriptionLablList[i]);
gradesLabel.Add(new Label());
gradesLabel[i].Text = _weatherForecast.WeatherList[i].Main.Temperature.ToString("0") + " C°";
gradesLabel[i].Location = new Point(xLocation + 200, yLocation);
gradesLabel[i].Font = new Font("Lucida Sans", 10, FontStyle.Regular);
Controls.Add(gradesLabel[i]);
yLocation += 100;
}
for (int i = 0; i < dayNameLabelList.Count; i++)
{
dayNameLabelList[i].ForeColor = Color.White;
weatherDescriptionLablList[i].ForeColor = Color.White;
gradesLabel[i].ForeColor = Color.White;
}
}
You need to add event handlers to the combo for either SelectedIndexChangedEvent (if it's a non-editable combo), or TextUpdateEvent if it is (likely both in that latter case). Those event handlers then change the other controls as needed.

C# How can I run this code in a background thread?

So I've been stuck on this for a while. (Forms application)
I want this to run in the "Background".
I normally call it with the "search button".
So far I've read you can't access UI stuff in another thread? So how would I approach this and make the UI accessible while it loads the results and converts them into buttons?
Is there any easy way to do this for someone who just started out with C#?
Code below :
private void Search_Video_Youtube(string page)
{
YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer()
{
ApplicationName = this.GetType().ToString(),
ApiKey = "*MyApiKeyGoesHere*",
});
var listRequest = youtube.Search.List("snippet");
listRequest.Q = Youtube_SearchVideo_Box.Text;
listRequest.MaxResults = 50;
listRequest.Type = "video";
listRequest.PageToken = nextPageToken;
video_results_vids = video_results_vids + 50;
var resp = listRequest.Execute();
List<string> videos = new List<string>();
foreach (SearchResult result in resp.Items)
{
switch (result.Id.Kind)
{
case "youtube#video":
PictureBox picturebox = new PictureBox();
picturebox.Height = 100;
picturebox.Width = 100;
picturebox.BorderStyle = BorderStyle.None;
picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
string template2 = "http://i3.ytimg.com/vi/{0}{1}";
string data2 = result.Id.VideoId.ToString();
string quality2 = "/default.jpg";
string messageB = string.Format(template2, data2, quality2);
var request = WebRequest.Create(messageB);
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
picturebox.Image = Bitmap.FromStream(stream);
}
flowLayoutPanel1.Controls.Add(picturebox);
listnumber += 1;
Button button = new Button();
button.Text = listnumber.ToString() + " " + result.Snippet.Title.ToString();
button.Tag = result.Id.VideoId;
button.TextImageRelation = TextImageRelation.ImageBeforeText;
button.FlatStyle = FlatStyle.Flat;
button.ForeColor = Color.LightSteelBlue;
button.BackColor = Color.SteelBlue;
button.Width = (flowLayoutPanel1.Width - 150);
button.TextAlign = ContentAlignment.MiddleLeft;
button.Height = 100;
button.Font = new Font(button.Font.FontFamily, 10);
button.Click += (s, e) => {
Youtube_video_Player_hider.Visible = false;
var a = result.Id.VideoId;
string template = "https://www.youtube.com/v/{0}{1}";
string data = a.ToString();
string quality = Video_Quality;
string messagea = string.Format(template, data, quality);
axShockwaveFlash1.Movie = messagea;
axShockwaveFlash1.Play();
};
flowLayoutPanel1.Controls.Add(button);
break;
}
}
nextPageToken = resp.NextPageToken;
toolStripStatusLabel1.Text = "Status : Idle";
toolStripStatusLabel2.Text = "Results : " + video_results_vids;
}
Any help is welcome but please explain it in detail as I am very new to C# but I do have a basic programming knowledge.
(Also if you see anything I could do better feel free to point it out, am here to learn :) )
EDIT : Thanks to Jeroen van langen (Answer below) I figured it out.
The current code is now :
// At using Stuff
using ExtensionMethods;
private void Search_Video_Youtube(string page)
{
ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
{
YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer()
{
ApplicationName = this.GetType().ToString(),
ApiKey = "ThisIsTheApiKeyYouTubeWantsForAnyoneWondering",
});
var listRequest = youtube.Search.List("snippet");
listRequest.Q = Youtube_SearchVideo_Box.Text;
listRequest.MaxResults = 50;
listRequest.Type = "video";
listRequest.PageToken = nextPageToken;
video_results_vids = video_results_vids + 50;
var resp = listRequest.Execute();
List<string> videos = new List<string>();
Parallel.ForEach(resp.Items, (SearchResult result) =>
{
switch (result.Id.Kind)
{
case "youtube#video":
string template2 = "http://i3.ytimg.com/vi/{0}{1}";
string data2 = result.Id.VideoId.ToString();
string quality2 = "/default.jpg";
string messageB = string.Format(template2, data2, quality2);
Image image;
var request = WebRequest.Create(messageB);
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
image = Bitmap.FromStream(stream);
}
listnumber += 1;
this.Invoke(() =>
{
PictureBox picturebox = new PictureBox();
picturebox.Height = 100;
picturebox.Width = 100;
picturebox.Image = image;
picturebox.BorderStyle = BorderStyle.None;
picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
flowLayoutPanel1.Controls.Add(picturebox);
Button button = new Button();
button.Text = listnumber.ToString() + " " + result.Snippet.Title.ToString();
button.Tag = result.Id.VideoId;
button.TextImageRelation = TextImageRelation.ImageBeforeText;
button.FlatStyle = FlatStyle.Flat;
button.ForeColor = Color.LightSteelBlue;
button.BackColor = Color.SteelBlue;
button.Width = (flowLayoutPanel1.Width - 150);
button.TextAlign = ContentAlignment.MiddleLeft;
button.Height = 100;
button.Font = new Font(button.Font.FontFamily, 10);
button.Click += (s, e) =>
{
Youtube_video_Player_hider.Visible = false;
var a = result.Id.VideoId;
string template = "https://www.youtube.com/v/{0}{1}";
string data = a.ToString();
string quality = Video_Quality;
string messagea = string.Format(template, data, quality);
axShockwaveFlash1.Movie = messagea;
axShockwaveFlash1.Play();
};
flowLayoutPanel1.Controls.Add(button);
});
break;
}
nextPageToken = resp.NextPageToken;
this.Invoke(() =>
{
toolStripStatusLabel1.Text = "Status : Idle";
toolStripStatusLabel2.Text = "Results : " + video_results_vids;
});
});
}));
}
Class Contents :
using System;
using System.Windows.Forms;
namespace ExtensionMethods
{
public static class MyExtensions
{
public static void Invoke(this Control control, Action action)
{
control.Invoke((Delegate)action);
}
}
}
You should execute the 'whole' method on a thread. Try to move all creation of controls to one section and invoke that part on the GUI thread. The most consuming time will be the WebRequests
PSEUDO: something like:
private void Search_Video_Youtube(string page)
{
ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
{
YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer()
{
ApplicationName = this.GetType().ToString(),
ApiKey = "*MyApiKeyGoesHere*",
});
var listRequest = youtube.Search.List("snippet");
listRequest.Q = Youtube_SearchVideo_Box.Text;
listRequest.MaxResults = 50;
listRequest.Type = "video";
listRequest.PageToken = nextPageToken;
video_results_vids = video_results_vids + 50;
var resp = listRequest.Execute().OfType<SearchResult>();
List<string> videos = new List<string>();
Parallel.Foreach(resp.Items, (result) =>
{
switch (result.Id.Kind)
{
case "youtube#video":
string template2 = "http://i3.ytimg.com/vi/{0}{1}";
string data2 = result.Id.VideoId.ToString();
string quality2 = "/default.jpg";
string messageB = string.Format(template2, data2, quality2);
Bitmap image;
var request = WebRequest.Create(messageB);
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
image = Bitmap.FromStream(stream);
}
listnumber += 1;
this.Invoke(() =>
{
PictureBox picturebox = new PictureBox();
picturebox.Height = 100;
picturebox.Width = 100;
picturebox.Image = image;
picturebox.BorderStyle = BorderStyle.None;
picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
flowLayoutPanel1.Controls.Add(picturebox);
Button button = new Button();
button.Text = listnumber.ToString() + " " + result.Snippet.Title.ToString();
button.Tag = result.Id.VideoId;
button.TextImageRelation = TextImageRelation.ImageBeforeText;
button.FlatStyle = FlatStyle.Flat;
button.ForeColor = Color.LightSteelBlue;
button.BackColor = Color.SteelBlue;
button.Width = (flowLayoutPanel1.Width - 150);
button.TextAlign = ContentAlignment.MiddleLeft;
button.Height = 100;
button.Font = new Font(button.Font.FontFamily, 10);
button.Click += (s, e) => {
Youtube_video_Player_hider.Visible = false;
var a = result.Id.VideoId;
string template = "https://www.youtube.com/v/{0}{1}";
string data = a.ToString();
string quality = Video_Quality;
string messagea = string.Format(template, data, quality);
axShockwaveFlash1.Movie = messagea;
axShockwaveFlash1.Play();
};
flowLayoutPanel1.Controls.Add(button);
});
break;
}
nextPageToken = resp.NextPageToken;
this.Invoke(() =>
{
toolStripStatusLabel1.Text = "Status : Idle";
toolStripStatusLabel2.Text = "Results : " + video_results_vids;
});
}, null);
}
Create a delegate that takes argument of type of resp
public delegate void ListDispatcher(var resp)
remember, var needs to be replaced with the exact type of the resp.
Now create a ListDispatcher reference member in the main class.
public ListDispatcher dispatcher;
and add a new method to its invocation list.
dispatcher += MyNewMethod;
Define the new method as
public void MyNewMethod(var resp){
//Move all your controls creation code here
}
Remove the code after the call
var resp = listRequest.Execute();
and simply put there
dispatcher(resp);
Now you can safely call the Search_Video_Youtube(string page) in a separate thread.

How do I draw a grid with 3 columns where 2 columns size to content?

So I want to draw a grid with 3 columns so that I can have:
Cancel Title Save
But at the moment I am getting
Cancel Title Save
The code I have is:
var modalContentPage = sender as ModalContentPage;
var context = Android.App.Application.Context;
var actionBar = ((Activity)Context).ActionBar;
LinearLayout gridView = new LinearLayout(context);
gridView.SetGravity(GravityFlags.FillHorizontal|GravityFlags.CenterVertical);
LinearLayout.LayoutParams textViewParameters =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent);
Android.Widget.Button cancelButton = new Android.Widget.Button(context);
cancelButton.Text = "Cancel";
cancelButton.Click += delegate
{
modalContentPage.CancelCommand.Execute(null);
};
gridView.AddView(cancelButton, LayoutParams.WrapContent);
TextView modelTitle = new TextView(context);
modelTitle.Text = actionBar.Title;
modelTitle.TextFormatted = actionBar.TitleFormatted;
modelTitle.Gravity = GravityFlags.Center;
modelTitle.TextSize = 25;
modelTitle.SetTypeface(Android.Graphics.Typeface.Default, Android.Graphics.TypefaceStyle.Bold);
modelTitle.SetTextColor(Android.Graphics.Color.White);
gridView.AddView(modelTitle);
Android.Widget.Button saveButton = new Android.Widget.Button(context);
saveButton.Text = "Save";
saveButton.Click += delegate
{
modalContentPage.SaveCommand.Execute(null);
};
saveButton.Background.SetColorFilter((Resources.GetColor(Resource.Color.accent)),Android.Graphics.PorterDuff.Mode.Multiply);
saveButton.Gravity = GravityFlags.Center;
gridView.AddView(saveButton,LayoutParams.WrapContent);
ActionBar.LayoutParams actionbarParams =
new ActionBar.LayoutParams(ActionBar.LayoutParams.MatchParent, ActionBar.LayoutParams.MatchParent);
actionBar.SetCustomView(gridView, actionbarParams);
actionBar.SetDisplayShowCustomEnabled(true);
actionBar.SetIcon(new ColorDrawable(Color.Transparent.ToAndroid()));
actionBar.SetDisplayHomeAsUpEnabled(false);
All i needed to add was:
modelTitle.LayoutParameters = new TableRow.LayoutParams(0, LayoutParams.WrapContent, 1f);

Create dynamic imagebuttons in a while loop and fire their events without using gridview

I'm trying to do these:
access my site's contents and read theme from my database
dynamically create a table without using grid-view and dynamically generate Image Buttons in
it to edit and delete my contents.
I Succeed to define a Post Back URL for one of my image buttons and post it to a new page with my content ID to edit it but I failed to define an event and fire it for delete my content without going to a new page.
Here is my code :
var cn = new SqlConnection();
var cmd = new SqlCommand();
int i=0;
try
{
using (cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnString"].ToString()))
{
cn.Open();
using (cmd = new SqlCommand("ContentArchiveCategory", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CatID", txtCategories.SelectedValue);
var dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
i++;
if (i % 2 != 0)
{
var tr = new TableRow();
tr.CssClass = "ADACLTOdd".ToString();
var no = new TableCell();
no.Text = i.ToString();
no.CssClass = "ADACLTNoColumn".ToString();
tr.Cells.Add(no);
var date = new TableCell();
date.Text = dr["DateCreated"].ToString();
date.CssClass = "ADACLTDateColumn".ToString();
tr.Cells.Add(date);
var title = new TableCell();
title.Text = dr["Title"].ToString();
title.CssClass = "ADACLTTitleColumn".ToString();
tr.Cells.Add(title);
var edit = new TableCell();
edit.CssClass = "ADACLTEditColumn".ToString();
var ice = new ImageButton();
ice.ImageUrl = "~/Images/ICSEdit.png".ToString();
ice.PostBackUrl = "ContentEdit.aspx?id=" + dr["ContentID"].ToString();
ice.ToolTip = "ویرایش".ToString();
edit.Controls.Add(ice);
tr.Cells.Add(edit);
var delete = new TableCell();
delete.CssClass = "ADACLTDeleteColumn".ToString();
var icd = new ImageButton();
icd.ImageUrl = "~/Images/ICSDelete.png".ToString();
icd.ToolTip = "پاک".ToString();
icd.ID = dr["ContentID"].ToString();
icd.Click += new ImageClickEventHandler(icd_Click);
delete.Controls.Add(icd);
tr.Cells.Add(delete);
ContentListTable.Rows.Add(tr);
}
else
{
var tr = new TableRow();
tr.CssClass = "ADACLTEven".ToString();
var no = new TableCell();
no.Text = i.ToString();
no.CssClass = "ADACLTNoColumn".ToString();
tr.Cells.Add(no);
var date = new TableCell();
date.Text = dr["DateCreated"].ToString();
date.CssClass = "ADACLTDateColumn".ToString();
tr.Cells.Add(date);
var title = new TableCell();
title.Text = dr["Title"].ToString();
title.CssClass = "ADACLTTitleColumn".ToString();
tr.Cells.Add(title);
var edit = new TableCell();
edit.CssClass = "ADACLTEditColumn".ToString();
var ice = new ImageButton();
ice.ImageUrl = "~/Images/ICSEdit.png".ToString();
ice.PostBackUrl = "ContentEdit.aspx?id=" + dr["ContentID"].ToString();
ice.ToolTip = "ویرایش".ToString();
edit.Controls.Add(ice);
tr.Cells.Add(edit);
var delete = new TableCell();
delete.CssClass = "ADACLTDeleteColumn".ToString();
var icd = new ImageButton();
icd.ImageUrl = "~/Images/ICSDelete.png".ToString();
icd.ToolTip = "پاک".ToString();
icd.ID = dr["ContentID"].ToString();
icd.Click += icd_Click;
delete.Controls.Add(icd);
tr.Cells.Add(delete);
ContentListTable.Rows.Add(tr);
}
ContentListTable.Visible = true;
}
}
}
}
catch
{
CatMessage.Visible = true;
CatMessage.BorderColor = System.Drawing.ColorTranslator.FromHtml("#930000");
CatMessage.BackColor = System.Drawing.ColorTranslator.FromHtml("#F4B7B7");
CatMsg1.Text = string.Format("{0} عزیز! متاسفانه در برقراری ارتباط با سرور مشکلی پیش آمده، لطفاً این مورد را به مدیریت سایت گزارش کنید", Session["FirstName"]);
}
}
}
protected void icd_Click(object sender, EventArgs e)
{
ImageButton icd = sender as ImageButton;
CatMessage.Visible = true;
CatMessage.BorderColor = System.Drawing.ColorTranslator.FromHtml("#930000");
CatMessage.BackColor = System.Drawing.ColorTranslator.FromHtml("#F4B7B7");
CatMsg1.Text = string.Format("{0}",icd.ID);
}
I tried both ways icd.Click += icd_Click; and icd.Click += new ImageClickEventHandler(icd_Click); to fire my event but it didn't work at all.

Categories