Linkbutton Dynamically Click - asp.net

I have a problem with my project . I am creating link buttons dynamically to show the projects. When I click on a project it is firing and I can display link buttons of bugs dynamically . Now when I click on a bug , I want to display the description, dynamically too , but this click event is not firing , and I can't fix it .. This is my code .
private void LoadXmlBugs(XDocument xDocument)
{
//Load all bugs
IEnumerable<Bugs> data = from query in xDocument.Descendants("bugs")
where (((string)query.Element("bug_status") == "NEW") ||
((string)query.Element("bug_status") == "REOPENED") ||
((string)query.Element("bug_status") == "New"))
select new Bugs
{
Bug_Id = (string)query.Element("bug_id"),
Short_Desc = (string)query.Element("short_desc"),
Bug_Status = (string)query.Element("bug_status"),
Priority = (string)query.Element("priority"),
Creation_Ts = (string)query.Element("creation_ts"),
};
Bugs = new List<Bugs>(data);
string statut = Request.QueryString.Get("bug_status");
foreach (Bugs b in Bugs)
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.ImageUrl = ("~/Img/FolderIco.png");
PanelAllBugs.Controls.Add(img);
LinkButton lkButtonBugs = new LinkButton();
lkButtonBugs.Click += new EventHandler(lkButtonBugs_Click);
lkButtonBugs.ID = b.Bug_Id;
lkButtonBugs.Tag = b.Short_Desc;
lkButtonBugs.Text = b.Bug_Status + " " + b.Short_Desc + " " + "<br>";
lkButtonBugs.Attributes.Add("runat", "server");
PanelAllBugs.Controls.Add(lkButtonBugs);
}
}
void lkButtonBugs_Click(object sender, EventArgs e)
{
bugId = ((sender as LinkButton).ID);
LoadTheDescriptionForABug(bugId, ((sender as LinkButton).ID));
LoadBugsComments();
LoadBugsAttachments();
}
Can someone help me ?
Thank you very much .

from where do you call the method: LoadXmlBugs ?
dynamically added controls should be added at every PostBack so everything depends on where/when you are calling the method above.
try to call LoadXmlBugs from the Page_Init event handler.

Related

Object reference not set to an instance of an object. This happens while adding checkboxlist control dynamically

Object reference not set to an instance of an object.
protected void cmdSave_Click(object sender, EventArgs e)
{
string strNames = string.Empty;
CheckBoxList Chkboxx = (CheckBoxList)PlaceHolder1.FindControl("Chkbox");
foreach (ListItem em in Chkboxx.Items) //-------- (Showing error)
{
if (em.Selected)
{
strNames += em.Value + ", ";
}
}
string final_name = strNames.Substring(0, strNames.Length - 2);
lblNames.Text = final_name;
}
Actually I am adding Checkbox control dynamically :
protected void ddl_varient_SelectedIndexChanged1(object sender, EventArgs e)
{
string query = "select prd_vrtyvalue_id,varient_value from tbl_ProductVariety_Value where varient='" + ddl_varient.SelectedItem.Text + "' " +
" order by varient_value asc ";
DataTable abc = new DataTable();
SqlDataAdapter ada = new SqlDataAdapter(query, new CommonClass().connection());
ada.Fill(abc);
ChkboxList.ID = "Chkbox";
for (int i = 0; i < abc.Rows.Count; i++)
{
ChkboxList.Items.Add(new ListItem(abc.Rows[i]["varient_value"].ToString(), abc.Rows[i]["prd_vrtyvalue_id"].ToString()));
}
ChkboxList.RepeatColumns = 2;
PlaceHolder1.Controls.Add(ChkboxList);
}
Can Anybody tell me, what exactly i am doing wrong !
The way ASP.NET WebForms work is that the entire page is re-built during each post back. So, I imagine this is what is occuring:
Page gets "built" and includes only controls defined within your ASCX/ASPX file.
User clicks on DDL_VARIENT checkbox and the ChkboxList is added to PlaceHolder1
Form is rendered back to the user so they can see ChkboxList
Save button is clicked, causing another postback.
Page is re-built, setting all the controls back to what is defined within your ASPX/ASCX code. This does not include ChkboxList.
Your code is hit, ChkboxList no longer exists and you get your problem.
To fix, you could re-add your ChkboxList on Page_Load depending on the value of your DDL_VARIENT checkbox. If I were you though, I'd be tempted to define the ChkboxList within your ASPX/ASCX code and then set the visibility of the list depending on the value of the DDL_VARIENT checkbox within Page_Load.
I should add, the entire of the above is dependant upon you using ASP.NET WebForms. If you're using MVC then it's probably wrong.

Setting selected value to DropDownList in UserControl

Could someone help me with setting the selected value of the DropDownList to the database given value. I have couple of TextBoxes for which it isn't hard to set the value from the database, but what drives me crazy is DropDownList.
<asp:TextBox ID="txtNaziv" runat="server" Width="430px" Text='<%# DataBinder.Eval(Container, "DataItem.Naziv") %>'></asp:TextBox>
As far as I know, it isn't possible to set the selected item value from the code front to the DropDownList, but I was able to find out something like this (code snippet from Telerik's RadGrid documentation):
protected void EmployeeDetails_DataBinding(object sender, System.EventArgs e)
{
ArrayList tocs = new ArrayList(new string[] { "Dr.", "Mr.", "Mrs.", "Ms." });
ddlTOC.DataSource = tocs;
ddlTOC.DataBind();
object tocValue = DataBinder.Eval(DataItem, "TitleOfCourtesy");
if (tocValue == DBNull.Value)
{
tocValue = "Mrs.";
}
ddlTOC.SelectedIndex = tocs.IndexOf((string)tocValue);
ddlTOC.DataSource = null;
}
The problem is I'm using Linq-to-SQL and I'm not sure how to recreate something like the above code. This is what I currently have:
protected void ddlTip_DataBinding(object sender, EventArgs e)
{
TSEntities db = new TSEntities();
var partType = (from pt in db.PartType
select new { pt.idPartType, pt.Naziv }).ToArray();
ddlTip.DataSource = partType;
ddlTip.DataTextField = "Naziv";
ddlTip.DataValueField = "idPartType";
ddlTip.DataBind();
object Tip = DataBinder.Eval(DataItem, "idPartType");
}
One more thing I have to add that this TextBoxes and DropDownList are inside the UserControl which is being used inside Telerik's RadGrid for its EditForm.
Any help would be appreciated.
Thank you!
You need to set the SelectedValue of the dropdown:
ddlTOC.SelectedValue = tocValue;
You can also do it like this:
ListItem li = ddlTOC.Items.FindByValue(tocValue);
if (li != null)
li.Selected = true;
EDIT:
Included code to bind list directly to db.PartType:
TSEntities db = new TSEntities();
ddlTip.DataSource = db.PartType;
ddlTip.DataTextField = "Naziv";
ddlTip.DataValueField = "idPartType";
ddlTip.DataBind();
ddlTip.SelectedValue = DataBinder.Eval(DataItem, "idPartType").ToString();
Try this one
ddlTip.Items.FindByValue(tocs).Selected = true;

Two Button Columns on a GridView Control

I have a grid view will two different button columns. I want to perform a different action depending on what button the user presses. How in the SelectedIndexChanged event do I determine what column was pressed. This is the code I use to generate the columns.
grdAttachments.Columns.Clear();
ButtonField bfSelect = new ButtonField();
bfSelect.HeaderText = "View";
bfSelect.ButtonType = ButtonType.Link;
bfSelect.CommandName = "Select";
bfSelect.Text = "View";
ButtonField bfLink = new ButtonField();
bfLink.HeaderText = "Link/Unlink";
bfLink.ButtonType = ButtonType.Link;
bfLink.CommandName = "Select";
bfLink.Text = "Link";
grdAttachments.Columns.Add(bfSelect);
grdAttachments.Columns.Add(bfLink);
I think it would help if you give the buttons different CommandName properties.
Here is an MSDN example of reading CommandName in the GridView_RowCommand event, which specifically mentions your multiple-button situation:
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = CustomersGridView.Rows[index];
TableCell contactName = selectedRow.Cells[1];
string contact = contactName.Text;
// Display the selected author.
Message.Text = "You selected " + contact + ".";
}
}
string commandName = e.CommandName.ToString().Trim();
GridViewRow row = GridView1.Rows[Convert.ToInt32(e.CommandArgument)];
switch (commandName)
{
case "showName":
LClickName.Text = "You Clicked Show Name Button : \"" + row.Cells[1].Text + "\"";
break;
case "EditName":
LClickName.Text = "You Clicked Edit Name Button : \"" + row.Cells[1].Text + "\"";
break;
default: break;
}
Here is a sample for Multiple select Button in One Gridview
Multiple Select Button In One Gridview

How to create line breaks between dynamically generated labels in a placeholder?

This is the code below in code behind file's Page_Load event:
LinkButton linkButton = new LinkButton();
linkButton.ID = "LinkButtonDynamicInPlaceHolder1Id" + i;
linkButton.ForeColor = Color.Blue;
linkButton.Font.Bold = true;
linkButton.Font.Size = 14;
linkButton.Font.Underline = false;
linkButton.Text = itemList[i].ItemTitle.InnerText;
linkButton.Click += new EventHandler(LinkButton_Click);
linkButton.Attributes.Add("LinkUrl",itemList[i].ItemLink.InnerText);
PlaceHolder1.Controls.Add(linkButton);
Label label = new Label();
label.ID = "LabelDynamicInPlaceHolder1Id" + i;
label.ForeColor = Color.DarkGray;
label.Text = itemList[i].ItemDescription.InnerText;
PlaceHolder1.Controls.Add(label);
I want a line break between each control generated.
Solution to your Line Break issue is below however, if you're doing this in the Page_Load event, then your event handlers won't work and your going to run into Page Life Cycle issues. Basically, in order for your event handlers to fire on PostBack, you really need to be creating these dynamic controls earlier in the Page Life Cycle. Try moving your code to the OnInit method if you do run into this problem.
LinkButton linkButton = new LinkButton();
linkButton.ID = "LinkButtonDynamicInPlaceHolder1Id" + i;
linkButton.ForeColor = Color.Blue;
linkButton.Font.Bold = true;
linkButton.Font.Size = 14;
linkButton.Font.Underline = false;
linkButton.Text = itemList[i].ItemTitle.InnerText;
linkButton.Click += new EventHandler(LinkButton_Click);
linkButton.Attributes.Add("LinkUrl",itemList[i].ItemLink.InnerText);
PlaceHolder1.Controls.Add(linkButton);
//Add This
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
Label label = new Label();
label.ID = "LabelDynamicInPlaceHolder1Id" + i;
label.ForeColor = Color.DarkGray;
label.Text = itemList[i].ItemDescription.InnerText;
PlaceHolder1.Controls.Add(label);
Another solution is that you could add each control to a Panel, which will render them each in a <div> resulting in the effect you're looking for.
To me this would be more dynamic because if you hide any of the controls the div will collapse and not leave empty lines.
LinkButton linkButton = new LinkButton();
linkButton.ID = "LinkButtonDynamicInPlaceHolder1Id" + i;
linkButton.ForeColor = Color.Blue;
linkButton.Font.Bold = true;
linkButton.Font.Size = 14;
linkButton.Font.Underline = false;
linkButton.Text = itemList[i].ItemTitle.InnerText;
linkButton.Click += new EventHandler(LinkButton_Click);
linkButton.Attributes.Add("LinkUrl",itemList[i].ItemLink.InnerText);
//Add control to a panel, add panel to placeholder
Panel lbPan = new Panel();
lbPan.Controls.Add(linkButton);
PlaceHolder1.Controls.Add(lbPan);
Label label = new Label();
label.ID = "LabelDynamicInPlaceHolder1Id" + i;
label.ForeColor = Color.DarkGray;
label.Text = itemList[i].ItemDescription.InnerText;
//Add control to a panel, add panel to placeholder
Panel lblPan = new Panel();
lblPan.Controls.Add(label);
PlaceHolder1.Controls.Add(lblPan);
How to: Add Controls to an ASP.NET Web Page Programmatically
In some instances, you might want to
create both static text and controls.
To create static text, you can use either a Literal or a Label Web server
control. You can then add these
controls to the container as you would
any other control. For information
about view state in controls created
at run time, see Dynamic Web Server
Controls and View State.

UpdatePanel doesn't Refresh

I have got a simple page with a HtmlInputHidden field. I use Javascript to update that value and, when posting back the page, I want to read the value of that HtmlInputHidden field. The Value property of that HtmlInputHidden field is on postback the default value (the value it had when the page was created, not the value reflected through the Javascript). I also tried to Register the HtmlInputHidden field with ScriptManager.RegisterHiddenField(Page, "MyHtmlImputHiddenField", "initialvalue") but it still only lets me read the 'initialvalue' even though I (through javascript) can inspect that the value has changed.
I tried to hardcoded the rowid and, to my surprise, after postback gridview was exactly the same before the delete but the record was deleted from the database. (I´ve called the databind method).
protected void gridViewDelete(object sender, GridViewDeleteEventArgs e)
{
bool bDelete = false;
bool bCheck = false;
if (hfControl.Value != "1")
{
// check relationship
bCheck = validation_method(.......);
if (bCheck)
{
bDelete = true;
}
}
else
{
hfControl.Value = "";
bDelete = true;
}
if (bDelete)
{
//process delete
}
else
{
string script = string.Empty;
script += " var x; ";
script += " x = confirm('are u sure?'); ";
script += " if (x){ " ;
script += " document.getElementById('hfControl').value = '1'; ";
script += " setTimeOut(__doPostBack('gridView','Delete$"
+ e.RowIndex + "'),0);";
script += " } ";
ScriptManager.RegisterClientScriptBlock(this,
Page.GetType()
, "confirm"
, script
,true);
}
}
On a postback, when the page loads is the view of the hidden field what was posted back or is it the value you set when the page loads? It may be that you have to worry about the case where in the postback you aren't resetting a value to what it was originally. Another point is that if you do a delete, are you refreshing the data that you show or is it the same? Those would be my suggestions.
When I do a postback the value is the same what was postedback. I think updatepanel wasnt refresh. I tried to do __doPostBack('UpdatePanel1',''), didnt work either.

Resources