Add event handler to RadGrid programmatically - c#

I've created a RadGrid programmatically and tried to bind a BatchEditCommand to it, but it's not updating and disappear after clicking the save more than one. The BatchEditCommand is not fired at all, no knowing what event is firing, it's hard for me to debug, maybe I've missed out some important setting when creating RadGrid?
for (int i = 1; i <= 1; i++)
{
strategy = strategy + Convert.ToString(i);
RadGrid RadGrid_Strategy = new RadGrid();
RadGrid_Strategy.ID = strategy;
RadGrid_Strategy.Skin = "Office2010Blue";
RadGrid_Strategy.GridLines = System.Web.UI.WebControls.GridLines.Both;
RadGrid_Strategy.DataSource = GetDataTableForStrategy(CY, i);
RadGrid_Strategy.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.Top;
RadGrid_Strategy.ShowHeader = false;
RadGrid_Strategy.BatchEditCommand += new GridBatchEditEventHandler(RadGrid_BatchEditCommand);
RadGrid_Strategy.MasterTableView.EditMode = GridEditMode.Batch;
RadGrid_Strategy.MasterTableView.BatchEditingSettings.EditType = GridBatchEditingType.Cell;
RadGrid_Strategy.AllowAutomaticUpdates = true;
RadGrid_Strategy.MasterTableView.CommandItemSettings.ShowAddNewRecordButton = false;
RadGrid_Strategy.MasterTableView.CommandItemSettings.ShowSaveChangesButton = true;
RadGrid_Strategy.MasterTableView.CommandItemSettings.ShowCancelChangesButton = true;
PlaceHolder1.Controls.Add(RadGrid_Strategy);
RadGrid_Strategy.Rebind();
}
Where BatchEditCommand is not firing at all:
protected void RadGrid_BatchEditCommand(object sender, GridBatchEditingEventArgs e)
{...}

The event you're trying to call can only get fired if you make changes to your grid, then call any of these client-side functions from the RadGrid's BatchEditingManager:
saveChanges(tableView)
saveAllChanges()
saveTableChanges(tableViews)
Check out this thread on the Telerik forums for more info.

Related

ASP.NET: How to avoid situation that dynamically created button event refreshes the page instead of doing relevant code

(Original text updated!)
I am slowly getting into ASP.NET, currently trying to make a small webforms app for a hackathon.
The page that I am having problems with is supposed to show a list of companies to which person can apply.
Since the list of those companies can change, company always can be added or removed, I want to make some kind of table which loads values dynamically. The table appears when a user clicks "View all companies", it shows a table with each row including the name of company and a button to move to the page of this company. At this stage, I am trying to make something even more simple, for the sake of testing.
So, the button should just display some kind of text.
But here's the problem.
When I click on the button, it just resets the page and as I understand, runs "Page_Load". The text is also resets to the value from Page_Load.
Now, I'll try to give code and try to give the best descriptions.
Here's the Page_Load, on first load it just displays the name of the user, and hides the table with company names. On non-first load, it should run click button events.
protected void Page_Load(object sender, EventArgs e)
{
HRGlobalHub.Code.Start.Firebase.thisFirebaseClient = new FireSharp.FirebaseClient(HRGlobalHub.Code.Start.Firebase.thisFirebaseConfig);
pnlCompaniesView.Visible = false;
if (!IsPostBack)
{
if (thisUser == null)
lblWelcomeUser.Text = "Welcome";
else
lblWelcomeUser.Text = "Welcome, " + thisUser.FirstName + " " + thisUser.LastName;
gCompany = new Code.Company.Company();
}
else
{
if (Action=="Apply")
btnApplyClick(this, e);
else if (Action == "Suggest")
btnSuggestClick(this, e);
if (Action == "View")
btnViewClick(this, e);
}
}
The code for showing all companies comes here:
protected async void btnViewAllCompanies_Click(object sender, EventArgs e)
{
ResetCompaniesTable();
lblWelcomeUser.Text = "ViewAll";
FirebaseResponse response = await HRGlobalHub.Code.Start.Firebase.thisFirebaseClient.GetTaskAsync("HRGlobalHub/Database/Companies/CompaniesList/");
HRGlobalHub.Code.Company.CompaniesNamesList thisData = response.ResultAs<HRGlobalHub.Code.Company.CompaniesNamesList>();
string[] CompanyArray = thisData.CompanyNameListVar.Split(',');
for (int i = 1; i < CompanyArray.Length; i++)
{
response = await HRGlobalHub.Code.Start.Firebase.thisFirebaseClient.GetTaskAsync("HRGlobalHub/Database/Companies/CompaniesDatabase/" + CompanyArray[i]);
HRGlobalHub.Code.Company.Company result = response.ResultAs<HRGlobalHub.Code.Company.Company>();
tbtTestTable.Rows.Add(NewCompanyRow(result));
}
pnlCompaniesView.Visible = true;
pnlCompaniesView.Width = 1100;
tbtTestTable.Width = 1100;
lblWelcomeUser.Text = tbtTestTable.Visible.ToString();
}
This part loads first just the names of companies, then full companies data from the server. Each company turns into a table row. It also creates OnClientClick button events, that should load on non-first Page Load.
public TableRow NewCompanyRow(HRGlobalHub.Code.Company.Company thisCompany)
{
TableRow newRow = new TableRow();
Button btnApply = new Button();
btnApply.Text = "Apply";
btnApply.OnClientClick += gCompany = thisCompany;
btnApply.OnClientClick += Action = "Apply";
Button btnSuggest = new Button();
btnSuggest.Text = "Suggest";
btnSuggest.OnClientClick += gCompany = thisCompany;
btnSuggest.OnClientClick += Action = "Suggest";
Button btnView = new Button();
btnView.Text = "View";
btnView.OnClientClick += gCompany = thisCompany;
btnView.OnClientClick += Action = "View";
TableCell[] Cells = new TableCell[6];
for (int i = 0; i < Cells.Length; i++)
Cells[i] = new TableCell();
Cells[0].Text = thisCompany.Name;
Cells[1].Text = thisCompany.FieldOfWork;
Cells[2].Text = thisCompany.Employees.Count.ToString();
Cells[3].Controls.Add(btnView);
Cells[4].Controls.Add(btnApply);
Cells[5].Controls.Add(btnSuggest);
for (int i = 0; i < Cells.Length; i++)
Cells[i].Width = 150;
newRow.Width = 900;
for (int i = 0; i < Cells.Length; i++)
newRow.Cells.Add(Cells[i]);
btnApply.Width = 150;
btnSuggest.Width = 150;
btnView.Width = 150;
return newRow;
}
Again, since it's just testing stage for this page, the button should only display the name of the company that it gets as variable.
void btnApplyClick(Object sender, EventArgs e, HRGlobalHub.Code.Company.Company thisCompany)
{
lblWelcomeUser.Text = "Apply to " + thisCompany.Name;
}
This works but only partly: whatever I try the code from Page Load always runs the last "mentioned" Action (which is "View") and always goes for the company from the last row.
Please help me solve this!
Evgenie
Solved it myself after all. In the end, the error was, that the dynamically created buttons also had to exist\be created at Page Load. So, I added the void for creating table with buttons at the Page Load, and just turned it invisible.
And I also added the !PostBack proposed in comments, but on it's own it wasn't enough.
Here's where I found out about this:
CommandEventArgs and Event question
However that started causing problems with buttons that needs to transit to another page. So, I added one more variable that is also checked at Page Load. If it is false, the Page works usually, if true then it moves to another page.
protected void Page_Load(object sender, EventArgs e)
{
HRGlobalHub.Code.Start.Firebase.thisFirebaseClient = new FireSharp.FirebaseClient(HRGlobalHub.Code.Start.Firebase.thisFirebaseConfig);
pnlCompaniesView.Visible = false;
if (!IsPostBack)
{
if (thisUser == null)
lblWelcomeUser.Text = "Welcome";
else
lblWelcomeUser.Text = "Welcome, " + thisUser.FirstName + " " + thisUser.LastName;
}
else if (Transit == true)
{
HRGlobalHub.Pages.Company.CreateCompany.thisUser = thisUser;
Server.Transfer("/Pages/Company/CreateCompany.aspx", false);
}
else if(Transit == false)
{
btnViewAllCompanies_Click(this, e);
pnlCompaniesView.Visible = false;
}
}
Buttons are created as before, no changes here:
Button btnApply = new Button();
btnApply.Text = "Apply";
btnApply.Click += (sender, EventArgs) => { btnApplyClick(sender, EventArgs, thisCompany); };
And the button that should transit to an other page, just changes the variable value:
protected void btnCreateCompany_Click(object sender, EventArgs e)
{
Transit = true;
}

Dynamic Textbox event TextChanged is not firing

I have a problem with a Dynamic Textbox event. I got other dynamic textbox with their textchanged events, the others work good, but this one never get into the event, the property AutoPostBack = true, EnabledViewState too, EnabledViewTheming too, and it's into an UpdatePanel and I create a Dynamic Trigger.
This is my code:
TextBox DescUnit = new TextBox();
DescUnit.ID = "DescUnit_txt" + (No).ToString();
DescUnit.Text = "0.0";
DescUnit.TextChanged += new EventHandler(DescUnit_TextChanged);
DescUnit.AutoPostBack = true;
DescUnit.EnableViewState = true;
DescUnit.EnableTheming = true;
Trgr = new PostBackTrigger();
Trgr.ControlID = DescUnit.ID;
UpdatePanel1.Triggers.Add(Trgr);
Table.Rows[i - 1].Cells[3].Controls.Add(DescUnit);
And this is the code of my Event
protected void DescUnit_TextChanged(object sender, EventArgs e)
{
Descuento_Row.Visible = true;
int i = 1;
foreach (HtmlTableRow Row in Tab.Rows)
{
if (Row.ID != null && String.Compare(Row.ID.Substring(0, 6), "TRDet_") == 0)
{
Detalle = (HtmlTable)(Row.Cells[0].Controls[0]);
if (sender.Equals(Detalle.Rows[1].Cells[3].Controls[0]))
{
TextBox Cantidad = new TextBox();
Clonar(Tab.Rows[i].Cells[1].Controls[0], Cantidad);
TextBox Precio = new TextBox();
Clonar(Tab.Rows[i].Cells[4].Controls[0], Precio);
TextBox DescUnit = new TextBox();
Clonar(Detalle.Rows[1].Cells[3].Controls[0], DescUnit);
TextBox ImpDesc = new TextBox();
Clonar(Detalle.Rows[2].Cells[4].Controls[0], ImpDesc);
ImpDesc_txt.Text = ((Convert.ToDouble(ImpDesc_txt.Text) - Convert.ToDouble(ImpDesc.Text)) + (Convert.ToDouble((Convert.ToDouble(DescUnit.Text) / 100)) * (Convert.ToDouble(Precio.Text) * Convert.ToInt32(Cantidad.Text)))).ToString();
ImpDesc.Text = (Convert.ToDouble((Convert.ToDouble(DescUnit.Text) / 100)) * (Convert.ToDouble(Precio.Text) * Convert.ToInt32(Cantidad.Text))).ToString();
Detalle.Rows[2].Cells[4].Controls.Clear();
Detalle.Rows[2].Cells[4].Controls.Add(ImpDesc);
}
i = i + 2;
}
}
}
But never get into it. Can anyone help me?
When ever we are creating controls in ASP.Net the controls can be create on form load or after it. But if you want events of the controls. you should initialize it in onInit Method. Then It will work properly.
If suppose I want to create dynamic textbox and its event. and want to add it in panel
Please refer following code.
protected override void OnInit(EventArgs e)
{
TextBox t = new TextBox();
t.ID = "t01";
t.TextChanged += t_TextChanged;
t.AutoPostBack = true;
Panel1.Controls.Add(t);
}
protected void t_TextChanged(object sender, EventArgs e)
{
}
Also please be sure that ID of the control is properly. Must interger,underscore and alphanumeric. ex t001, t_1 etc
But should not space.

How to raise a dynamically created event on a dynamically created winform control?

I have a CheckedListBox control that I created programatically from below...
Button btnSelectAll = new Button();
btnSelectAll.Text = "Select All";
btnSelectAll.Name = item.Id;
btnSelectAll.Tag = param.Id;
CheckedListBox chkListBox = new CheckedListBox();
chkListBox.Size = new System.Drawing.Size(flowPanel.Size.Width - lblListBox.Size.Width - 10, 100);
//set the name and tag for downstream event handling since two-way bindings are not possible with control
chkListBox.Tag = param.Id;
chkListBox.Name = item.Id;
chkListBox.ItemCheck += new ItemCheckEventHandler(chkListBox_ItemCheck);
btnSelectAll.Click += new EventHandler(btnSelectAll_Click);
Notice when I dynamically created the item, I also added an event handler whenever the ItemCheck on the chkListBox is hit. Somewhere else in the code... I do...
CheckedListBox tmpCheckedListBox = cntrl as CheckedListBox;
for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
tmpCheckedListBox.SetItemChecked(i, true);
}
When I do the above, it doens't raise the ItemChecked event. How do I raise this event such that it is as if a user clicked on the item?
One way is to just call the same method as assigned to the event and pass in the correct control for sender, for example:
for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
tmpCheckedListBox.SetItemChecked(i, true);
chkListBox_ItemCheck(tmpCheckedListBox.Items[i],null);
}
You can usually get away with passing EventArgs.Empty or null as the event arguments, however if you depend on them in the event handler you would need to construct the correct arguments class and pass that in, for example:
for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
var args = new ItemCheckEventArgs(i,true,tmpCheckedListBox.GetItemChecked(i));
tmpCheckedListBox.SetItemChecked(i, true);
chkListBox_ItemCheck(tmpCheckedListBox.Items[i],args);
}

Customize double click for text box

private void newThumbNail(int docType, string fileName)
{
thmbNail[thmbNailCnt] = new GroupBox();
thmbNail[thmbNailCnt].Parent = panel1;
thmbNail[thmbNailCnt].Visible = true;
thmbNail[thmbNailCnt].Location = new Point(2, 5 + ((thmbNailCnt * 50) + 2));
thmbNail[thmbNailCnt].Size = new Size(222, 50);
picBox[thmbNailCnt] = new PictureBox();
picBox[thmbNailCnt].Parent = thmbNail[thmbNailCnt];
picBox[thmbNailCnt].Visible = true;
picBox[thmbNailCnt].Location = new Point(6, 13);
picBox[thmbNailCnt].Size = new Size(31, 31);
switch (docType)
{
case 1: picBox[thmbNailCnt].Image = wordImg;
break;
case 2: picBox[thmbNailCnt].Image = pptImg;
break;
case 3: picBox[thmbNailCnt].Image = excelImg;
break;
case 4: picBox[thmbNailCnt].Image = pdfImg;
break;
}
texBox[thmbNailCnt] = new TextBox();
texBox[thmbNailCnt].Parent = thmbNail[thmbNailCnt];
texBox[thmbNailCnt].Visible = true;
texBox[thmbNailCnt].Location = new Point(53, 24);
texBox[thmbNailCnt].Size = new Size(163, 20);
texBox[thmbNailCnt].Text = fileName;
texBox[thmbNailCnt].Enabled = false;
texBox[thmbNailCnt].BackColor = Color.Silver;
texBox[thmbNailCnt].ForeColor = Color.Black;
texBox[thmbNailCnt].DoubleClick += new System.EventHandler(changeText);
thmbNailFN[thmbNailCnt] = fileName;
data[thmbNailCnt, 0] = fileName;
data[thmbNailCnt, 1] = docType.ToString();
thmbNail[thmbNailCnt].Controls.Add(picBox[thmbNailCnt]);
thmbNail[thmbNailCnt].Controls.Add(texBox[thmbNailCnt]);
thmbNailCnt++;
}
private void changeText(object sender, EventArgs e)
{
this.Enabled = true;
}
The private void newThumbNail, adds a group box with picture box and text box as its elements. I have customize a double click event for the text Box, unfortunately it does not executes. Why is that so?
Your event won't fire because the TextBox is disabled. However I think the the solution might be a redesign of your interface since it is not expected behaviour for a control to be enabled when double-clicked. The whole point of disabling a control is to prevent a user from interacting with it.
Perhaps setting it to readonly might be a better option? That way it will still fire events.
The DoubleClick event will not fire on the TextBox if it is not enabled. So, it will not work because you are doing this:
texBox[thmbNailCnt].Enabled = false;
I presume you meant to do the following in the double click handler (instead of using this)
(sender as TextBox).Enabled = true;
You must be trying to make the textbox enable itself with a double click?
If so, then you can't use the Enabled property because the click events will not fire while your textbox is disabled.
Instead, you can use the ReadOnly property which will prevent the user from making any changes to the text:
texBox[thmbNailCnt].ReadOnly = true;
and
private void changeText(object sender, EventArgs e)
{
(sender as TextBox).ReadOnly = false;
}
This will not give it the dimmed out look it has when it is disabled. You could make some aditional changes to get it looking the same though if you wanted.

Click event for dynamically created link buttons not firing?

This is application i am doing in c# web application
I am creating link buttons dynamically as below.
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
LinkButton ln = new LinkButton();
ln.Text = ds.Tables[0].Rows[i].ItemArray[0].ToString();
ln.ID = ds.Tables[0].Rows[i].ItemArray[1].ToString();
divonlne.Controls.Add(ln);
divonlne.Controls.Add(new LiteralControl("<br/>"));
}
my click event is as follows
ln.Click += new EventHandler(Clicked);
In my click event i am getting the linkbutton text and Id as follows
protected void Clicked(object sender, EventArgs e)
{
LinkButton lno = sender as LinkButton;
Session["Toname"] = lno.Text;
Session["idto"] = lno.ID;
}
But this is firing only when the last link button is clicked.
Can anyone help me out?
You already wrote how you subscribe the Click Event, but in your sample i cant see it.
Maybe you subscribe on the wrong place. This works...
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
LinkButton ln = new LinkButton();
ln.Text = ds.Tables[0].Rows[i].ItemArray[0].ToString();
ln.ID = ds.Tables[0].Rows[i].ItemArray[1].ToString();
ln.Click += new EventHandler(Clicked);
divonlne.Controls.Add(ln);
divonlne.Controls.Add(new LiteralControl("<br/>"));
}
When using dynamic controls in a custom control, remember to decorate your class with the INamingContainer interface. This ensures recreated controls fit correctly into the hierarchy and remember which events they are supposed to handle.

Categories