Pass additional variable to button_click() method - c#

I am creating a dynamic table for listing files.
It shows filename, filesize, dateModified columns. In addition, I have added one more columns: Delete.
The method which lists files of a folder in a table.
public void listFile()
{
var dir = new DirectoryInfo(selectedFolder);
Table fileTable = new Table();
foreach (var file in dir.GetFiles())
{
TableRow tr = new TableRow();
TableCell td1 = new TableCell();
TableCell td2 = new TableCell();
TableCell td3 = new TableCell();
TableCell td4 = new TableCell();
Label name = new Label();
Label size = new Label();
Label dateMod = new Label();
LinkButton btn_delete = new LinkButton();
name.Text = file.Name;
size.Text = (file.Length / 1024) + " KB";
dateMod.Text = file.LastWriteTime.ToLongTimeString();
btn_delete.Text = "Delete";
btn_delete.Click += new EventHandler(btn_delete_Click);
td1.Controls.Add(name);
td2.Controls.Add(size);
td3.Controls.Add(dateMod);
td4.Controls.Add(btn_delete);
tr.Controls.Add(td1);
tr.Controls.Add(td2);
tr.Controls.Add(td3);
tr.Controls.Add(td4);
}
filePanel.Controls.Add(fileTable);
}
protected void btn_delete_Click(object sender, EventArgs e)
{
//Delete file
}
Now I want to delete the file when I click on the corresponding delete button. But problem is how will computer know which file to be deleted? I must pass the filename to the delete method.

You can pass command argument to the link button as mentioned below:
btn_delete.CommandArgument = [ID of the file]
and on click event of the link button you can access it as mentioned below:
protected void btn_delete_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
var id = btn.CommandArgument;
}
Reference: LinkButton.CommandArgument Property

The answer from SpiderCode and RePierre about using the CommandArgument is a correct. It might however help you to understand that the CommandArgument is nothing more than a thin wrapper around the ViewState concept.
ViewState is one way how you can transport data between client and server. If you ever run into a similar problem and you don't have commandargument available you can resort to viewstate.
Take a look at the LinkButton.cs
public string CommandArgument {
get {
string s = (string)ViewState["CommandArgument"];
return((s == null) ? String.Empty : s);
}
set {
ViewState["CommandArgument"] = value;
}
So you can either use the CommandArgument or use ViewState directly.

You can use the CommandArgument property of btn_delete to pass the path to the file:
btn_delete.CommandArgument = file.Name;
And in the event handler you just have to get the value as following:
protected void btn_delete_click(object sender, EventArgs e)
{
var button = sender as Button;
var filename = button.CommandArgument;
}

You can do this by creating a UserControl which is inheritated from the main Control.
In my example I extended a Textbox with an address variable.
In that way you bind a value to the control, which you can use later.
public class ExtendedTextBox : System.Windows.Forms.TextBox
{
private int? _Address = null;
[Description("Address of variable")]
[DefaultValue(null)]
public int? Address
{
get { return _Address; }
set { _Address = value; }
}
}

Related

Add multiple CommandArguments to button programmatically

I got some code to create new buttons programmatically.
foreach (DataRow dtRow in dtTable.Rows)
{
string question_id = Convert.ToString(dtRow["QUESTION_ID"]);
string question_text = Convert.ToString(dtRow["QUESTION_TEXT"]);
var btn_system = new Button
{
ID = "btn_question" + question_id,
Text = question_text,
CssClass = "quest_buttons"
};
btn_system.Command += ButtonClick_Parent;
btn_system.CommandArgument = Convert.ToString(question_id);
}
Now I would like to add multiple CommandArgument in line 12 of my code snippet. How can I do this from code behind?
Thanks in advance!
You need to pass multiple arguments as a string separating by some character and in event handler, you need to parse them. I have shown here using comma
btn_system.CommandArgument = "argument1,argument2,argument2,...";
then get this using below code
protected void ButtonClick_Parent(object sender, EventArgs e)
{
Button button = (Button)sender;
string[] commandArgs = button.CommandArgument.ToString().Split(',');
}

Not able to store information while postback after creating dynamic dropdown in ASP.NET

here is my code
after button 2 click event it is creating the dropdown in table rows but when I try to save by button 1 click event it just disappear. I have not find any solution regarding this. I have used find control view State etc but it's not helping.
I want to store selected values of dropdown after button_1 click event starts.
public partial class StudentClassSectionMapping : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ClassCode.Enabled = false;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
UpdateModalShowFlag.Value = "true";
Check.Value = "true";
CreateTableRows();
}
private void CreateTableRows()
{
long h = long.Parse(LinkButtonIdCarrier.Value);
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allStudentsInClass = StudentsClassSectionMapping.GetStudentsinClass(h);
ClassMaster.ClassMasterForm classCode = Schoolclasses.GetInfo(h);
ClassCode.Text = classCode.cCode;
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allSectionsInClass = StudentsClassSectionMapping.GetSectionsinClass(h);
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm studentList in allStudentsInClass)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TableCell cell3 = new TableCell();
DropDownList t = new DropDownList();
t.Items.Add("No Section");
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm sectionList in allSectionsInClass)
{
t.Items.Add(sectionList.ssSection);
t.Items[t.Items.Count - 1].Value = sectionList.ssSectionID.ToString();
}
t.Attributes.Add("class", "form-control");
t.ID = studentList.ssStudentId.ToString();
cell1.Text = studentList.ssName;
cell2.Text = studentList.ssRegistrationNumber;
cell3.Controls.Add(t);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
row.Cells.Add(cell3);
Table1.Rows.Add(row);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTableRows();
long h = long.Parse(LinkButtonIdCarrier.Value);
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allStudentsInClass = StudentsClassSectionMapping.GetStudentsinClass(h);
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm studentList in allStudentsInClass)
{
DropDownList d = Table1.FindControl(studentList.ssStudentId.ToString()) as DropDownList;
if (d != null)
{
if (d.SelectedIndex != 0)
{
StudentsClassSectionMapping.StudentsClassSectionMappingForm studentSectionMapping = new StudentsClassSectionMapping.StudentsClassSectionMappingForm();
studentSectionMapping.ssClassId = h;
studentSectionMapping.ssStudentId = studentList.ssStudentId;
studentSectionMapping.ssStudentId = long.Parse(d.SelectedItem.Value);
StudentsClassSectionMapping.addSectionStudentMapping(studentSectionMapping);
}
else
{
StudentsClassSectionMapping.StudentsClassSectionMappingForm studentSectionMapping = new StudentsClassSectionMapping.StudentsClassSectionMappingForm();
studentSectionMapping.ssClassId = h;
studentSectionMapping.ssStudentId = 0;
studentSectionMapping.ssStudentId = 0;
StudentsClassSectionMapping.addSectionStudentMapping(studentSectionMapping);
}
}
}
}
It get vanished/disappear because you added it dynamically on page. If you want it back or want to reserver control which is dynamically created you need to recreate again and need to add dynamically.
Here is good example of how you can do it : How to create controls dynamically in ASP.NET and retrieve values from it

Gridview Edit/Update is not working?

Here i am updating the gridview value but the value is not updating..TextBox txtID,TextBox txtName,TextBox txtAge retains the older value only and the value is not getting updated..Can anyone tel me like what am i doing wrong here
Here is my code
protected void gvTemp_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
int autoid = Int32.Parse(gvTemp.DataKeys[e.RowIndex].Value.ToString());
int id = Convert.ToInt32(gvTemp.DataKeys[e.RowIndex].Values[0].ToString());
activeTabIndex = Convert.ToInt16(Session["activeTabIndex"]);
TextBox txtID = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtId"));
TextBox txtName = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtName");
TextBox txtAge = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtAge");
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["ID"] = txtID.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Name"] = txtName.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Age"] = txtAge.Text;
gvTemp.DataSource = dataSetInSession.Tables["Days" + activeTabIndex.ToString()];
gvTemp.DataBind();
gvTemp.EditIndex = -1;
}
and
private void CreateDataSkeletton(int intTabIndex)
{
dataSetInSession = new DataSet();
Session["intTabIndex"] = intTabIndex;
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (dataSetInSession.Tables["Days" + intTabIndex].Rows.Count > 0)
{
gvTemp.DataSource = dataSetInSession.Tables["Days" + intTabIndex];
gvTemp.DataBind();
}
else
{
gvTemp.DataSource = dataSetInSession.Tables["Days"];
gvTemp.DataBind();
}
temp.Controls.Add(gvTemp);
}
Any suggestion??
EDIT(1):
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDataTable();
}
dataSetInSession = new DataSet();
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (Session["dynamicTabIDs"] != null)
{
//if dynamicTabIDs are in session, recreating the Tabs
//that are associated with the Tab IDs
//and adding them to the TabContainer that will contain
//all of the dynamic tabs.
//retrieving the tab IDs from session:
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
if (TabContainerContent.ActiveTabIndex == -1)
{
TabContainerContent.ActiveTabIndex = Convert.ToInt16(Session["intTabIndex"]);
}
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
//looping through each TabID in session
//and recreating the TabPanel that is associated with that tabID
foreach (string tabID in dynamicTabIDs)
{
//creating a new TabPanel that is associated with the TabID
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
//TabContainerContent.ActiveTabIndex = tab;
//Setting the ID property of the TabPanel
tab.ID = tabID;
//setting the TabPanel's HeaderText
tab.HeaderText = "Days " + (TabContainerContent.Tabs.Count + 1).ToString();
//creating a Label to add to the TabPanel...at this point you'll have to
//create whatever controls are required for the tab...
Label tabContent = new Label();
//Giving the Label an ID
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
//Setting the Label's text
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
//Adding the Label to the TabPanel
tab.Controls.Add(tabContent);
//Adding the TabPanel to the TabContainer that contains the dynamic tabs
TabContainerContent.Tabs.Add(tab);
}
}
else
{ //Creating a new list of dynamicTabIDs because one doesn't exist yet in session.
dynamicTabIDs = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Read Page Life Cycle
And you will get, that if you want to bind in code-behind, you should do it in Init Event, other wise there are no events will fire.
It seems to be Page.IsPostback problem.Need to add Page.IsPostback property in your page_load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Put your code inside that.
}
}
Actually your control is getting new value but when you click for updation then it calls old value from page_load.So try to put Page.IsPostback into your page_load event,Just like i mentioned.
I hope it helps.

CheckChanged event called when trying to switch to another TAB?

I have some radiobuttons on some tabs, when I click on one it generates an Excel-file.
<asp:RadioButton ID="rbAantallen1" runat="server" AutoPostBack="True"
GroupName="Soort" oncheckedchanged="rbRapport_CheckedChanged"
Text="Aantallen" />
The bug happens when I want to switch to the other tab. It keeps generating Excel-files. What can I do to stop running the checkedchanged event and SWITCH IN PEACE TO ANOTHER TAB?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MyDataSource.SelectCommand = #"
select melder_account,
aanvraag_titel,
fase_datum_opgelost_oplosser,
Melding_niveau_2,
rapporteren,
fase_datum_gestart,
fase_datum_opgelost,
doorlooptijd,
jurentkode
from uvw_HD_AANVRAAG_DOORLOOPTIJD_ALGEMEEN
where Melding_niveau_1 = 'Brandje'";
}
}
protected void MenuTabs_MenuItemClick(object sender, MenuEventArgs e)
{
int index = Int32.Parse(e.Item.Value);
multiTabs.ActiveViewIndex = index;
MyDataSource.SelectCommand = BepaalDataSource(index);
}
public string BepaalDataSource(int index)
{
string select = #"
select melder_account,
aanvraag_titel,
fase_datum_opgelost_oplosser,
Melding_niveau_2,
rapporteren,
fase_datum_gestart,
fase_datum_opgelost,
doorlooptijd,
jurentkode
from uvw_HD_AANVRAAG_DOORLOOPTIJD_ALGEMEEN
where Melding_niveau_1 = '";
if (index == 0)
{
cbPage.Checked = false;
return select += "Brandje'";
}
else
{
cbPage.Checked = true;
return select += "System - Netwerk'";
}
}
public DataView GetDataFromDataSource()
{
MyDataSource.SelectCommand = BepaalDataSource(Convert.ToInt16(cbPage.Checked));
return MyDataSource.Select(DataSourceSelectArguments.Empty) as DataView;
}
protected void rbRapport_CheckedChanged(object sender, EventArgs e)
{
DataTable dtOriginal = (DataTable)GetDataFromDataSource().ToTable(); //Return Table consisting data
DataTable dtTemp = new DataTable(); //Create Temporary Table
//Creating Header Row
dtTemp.Columns.Add("<b>Melder</b>");
dtTemp.Columns.Add("<b>Onderwerp</b>");
dtTemp.Columns.Add("<b>Oplosser</b>");
dtTemp.Columns.Add("<b>Niveau 2</b>");
dtTemp.Columns.Add("<b>Rapporteren</b>");
dtTemp.Columns.Add("<b>Gestart op</b>");
dtTemp.Columns.Add("<b>Opgelost op</b>");
dtTemp.Columns.Add("<b>Doorlooptijd</b>");
dtTemp.Columns.Add("<b>Jurentkode</b>");
DataRow drAddItem;
for (int i = 0; i < dtOriginal.Rows.Count; i++)
{
drAddItem = dtTemp.NewRow();
drAddItem[0] = dtOriginal.Rows[i][0].ToString();//Melder
drAddItem[1] = dtOriginal.Rows[i][1].ToString();//Onderwerp
drAddItem[2] = dtOriginal.Rows[i][2].ToString();//Oplosser
drAddItem[3] = dtOriginal.Rows[i][3].ToString();//Niveau 2
drAddItem[4] = dtOriginal.Rows[i][4].ToString();//Rapporteren
drAddItem[5] = dtOriginal.Rows[i][5].ToString();//Gestart op
drAddItem[6] = dtOriginal.Rows[i][6].ToString();//Opgelost op
drAddItem[7] = dtOriginal.Rows[i][7].ToString();//Doorlooptijd
drAddItem[8] = dtOriginal.Rows[i][8].ToString();//Jurentkode
dtTemp.Rows.Add(drAddItem);
}
DataGrid dg = new DataGrid(); //Temp Grid
dg.DataSource = dtTemp;
dg.DataBind();
ExportToExcel("Rapport.xls", dg);
dg = null;
dg.Dispose();
}
private void ExportToExcel(string strFileName, DataGrid dg)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
protected void cbRapport_CheckedChanged(object sender, EventArgs e)
{
}
A couple things come to mind.
In your rbRapport_CheckChanged() function you could check to make sure the radio button is visible.
You could also check your tab control to make sure you're on the right tab.
EDIT
Based on your comments, the hosting tab is invisible.
If that's the case, do something like this in your code
rbRapport_CheckChanged()
{
if(tab1.Visible == false)
return;
<rest of code here>
}
Where tab1 is the tab that rbRapport is on. This will check, if the tab isn't visible, you probably don't want to create an xls, so it will just short circuit and kick out of the event. If the tab is visible, it will process the event.
Edit
maybe you shouldn't be creating the xls when your radio button changes. Maybe you should have a button to click that says "Generate XLS" or something, and capture that click event. – taylonr Apr 28 at 11:42
Nothing wrong with the code provided. Please ensure that, you have not bind this rbRapport_CheckedChanged function with any other control's event like TabChangedEvent or CheckedChange event of other radio button which values will be changing based on tab change etc.
If not so, there may be problem with the parent controls of the RadioButton.

How to add a Hyperlink to a dynamic gridview column

I have an issue hope someone can help.
I have a dynamic Gridview. I need to have a hyperlink on gridview column. These hyperlink should open a popup to display certain data on clicking.
I tried this by having a dynamic template field . But even on binding the data , I'm unable to get the hyper link for the column. I'm able to get the data but not the hyperlink.
This is the HyperLinkTemplate class which is implementing ITemplate.
public class HyperLinkTemplate : ITemplate
{
private string m_ColumnName;
public string ColumnName
{
get { return m_ColumnName; }
set { m_ColumnName = value; }
}
public HyperLinkTemplate()
{
//
// TODO: Add constructor logic here
//
}
public HyperLinkTemplate(string ColumnName)
{
this.ColumnName = ColumnName;
}
public void InstantiateIn(System.Web.UI.Control ThisColumn)
{
HyperLink HyperLinkItem = new HyperLink();
HyperLinkItem.ID = "hl" + ColumnName;
HyperLinkItem.DataBinding += HyperLinkItem_DataBinding;
ThisColumn.Controls.Add(HyperLinkItem);
}
private void HyperLinkItem_DataBinding(object sender, EventArgs e)
{
HyperLink HyperLinkItem = (HyperLink)sender;
GridViewRow CurrentRow = (GridViewRow)HyperLinkItem.NamingContainer;
object CurrentDataItem = DataBinder.Eval(CurrentRow.DataItem, ColumnName);
HyperLinkItem.Text = CurrentDataItem.ToString();
}
}
I'm not entirely sure that I understand what you are trying to accomplish, but I don't think that you should have to build your own template class for this.
You might mean something other than what I'm thinking by the term "dynamic gridview", but if you need to add a hyperlink to each row of a column in a GridView, and if you need to do this in the code-behind, then I would suggest handling the GridView's RowDataBound event and doing something like the following in the event handler:
protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink link = new HyperLink();
link.Text = "This is a link!";
link.NavigateUrl = "Navigate somewhere based on data: " + e.Row.DataItem;
e.Row.Cells[ColumnIndex.Column1].Controls.Add(link);
}
}

Categories