I have a ASP.NET datagrid which is on a user control. I have a main page which adds the user control ( sometimes multiple copies of the user control ) and restores them when a post back occurs.
The dataGrid has insert / edit / delete links. I can add multiple copies of the user control to the page and the insert / edit delete functionality works perfectly for each separate control.
Yesterday I added some property binding to the main page to which are unrelated to the user control using the format Text='<%# DocumentTitle %>'. Initially I couldn't get this to work until I added Page.DataBind(); to the main page's Page_Load method. At this point the property binding started working correctly but then I noticed the insert functionality had stopped working in the datagrid within each user control....I debugged and found that when the following line executes it finds the text fields in the controls within the dataGrid to be empty or "":
eInfo.Ref = ((TextBox)gvEG.FooterRow.FindControl("txtEmployeeName")).Text;
If I remove the page.DataBind() method from the main page then the property binding stops working but the dataGrid(s) in the userControl start working.
My question is two fold i) Why does the seemingly unrelated change effect the dataGrid and ii) what do I do to get this working?
I've added the relevant sections of my code below...or at least what I think are the relevant sections.
Default.aspx
<div class="general">
<asp:TextBox Width="488" runat="server" placeholder="Document Title" Text='<%# DocumentTitle %>'></asp:TextBox>
</div>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Create an empty user control for the first requirements section.
EmployeeSectionUserControl myUserControl1 = (EmployeeSectionUserControl )LoadControl("~/EmployeeSectionUserControl .ascx");
// Add it to the panel control holding all the user controls.
MainPanel.Controls.Add(myUserControl1);
DocumentTitle = "I am the default document title and I'm bound.";
}
else
{
// Do nothing
}
Page.DataBind();
}
EmployeeSectionUserControl.ascx
<asp:GridView ID="gvEG" runat="server" AutoGenerateColumns="False" CssClass="grid"
AlternatingRowStyle-CssClass="gridAltRow" RowStyle-CssClass="gridRow" ShowFooter="True"
EditRowStyle-CssClass="gridEditRow" FooterStyle-CssClass="gridFooterRow" OnRowCancelingEdit="gvEG_RowCancelingEdit"
OnRowCommand="gvEG_RowCommand" OnRowDataBound="gvEG_RowDataBound" OnRowDeleting="gvEG_RowDeleting"
OnRowEditing="gvEG_RowEditing" OnRowUpdating="gvEG_RowUpdating" DataKeyNames="Id" ShowHeaderWhenEmpty="true">
<Columns>
<asp:TemplateField HeaderText="Id" HeaderStyle-HorizontalAlign="Left" ControlStyle-Width="50px">
<ItemTemplate>
<%# Eval("Id")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ref" HeaderStyle-HorizontalAlign="Left" ControlStyle-Width="90px">
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Ref") %>'
Width="90px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Width="90px"></asp:TextBox>
</FooterTemplate>
EmployeeSectionUserControl.ascx.cs
protected void gvEG_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
employeeInfo eInfo = new employeeInfo();
eInfo.Id = 999;// Convert.ToInt32(((TextBox)gvEG.FooterRow.FindControl("Id")).Text);
// If we're inserting from the EmptyDataTemplate( ie an empty table ) of the gridview then we need to retreive the data differently.
// So we perform a check on the gridView FooterRow and if it's null then we can assume it's an empty table.
if (gvEG.FooterRow == null)
{
TextBox referenceTxtBox = (((Control)e.CommandSource).NamingContainer).FindControl("txtEmployeeName") as TextBox;
eInfo.Ref = referenceTxtBox.Text;
}
else
{
eInfo.Ref = ((TextBox)gvEG.FooterRow.FindControl("txtEmployeeName")).Text;
eInfo.Need =
}
// Store Update and Re-bind data to grid.
}
}
Page.DataBind() calls DataBind on it's children, so it updates DocumentTitle in the text box but it also DataBinds your grid. I didn't see a DataSource set in your grid, like an EntityDataSource, so I am assuming you are doing the smart retrieving (and preparation) of the data yourself in code and set the DataSource yourself:
gvEg.DataSource = someCollection;
gvEg.DataBind();
On the get your are loading the user-control and probably call this DataBind with specifying the DataSource. It binds and then you call Page.DataBind() which probably also triggers another DataBind for gvEg but since DataSource is set it shows the same.
On the post back you shouldn't do a DataBind() before handling events. Your call of Page.DataBind() does that. It triggers a DataBind() without a DataSource. Then the rowCommand comes and checks for the TextBox in the Footer which is cleared due to a DataBind with no elements.
What you should do is:
You shouldn't use Page.DataBind(). If you do so, you need todo it at a moment when all DataSources are set correctly and it shouldn't be kicked of during a post back. In general, I would not recommend using it because it makes it more complex and it's probably only helping a bit if you haven't set up your application correctly.
In your case it's definitely not necessary. Your textBox is a server control that's not part of any binding (GridView, Repeater, ListView). So your textBox is immediately available in your code behind.
So you should:
Give the textBox an ID you can use like txtDocumentTitle
<asp:TextBox Width="488" ID="txtDocumentTitle" runat="server" placeholder="Document Title"></asp:TextBox>
Replace setting DocumentTitle (unless you need it for something else too) with:
txtDocumentTitle.Text = "I am the default document title and I'm bound.";
Remove Page.DataBind();
So access server controls you have access immediately since they are also properties in your page or control.
Related
I'm currently trying to create a web based wizard tool. I have a Wizard page that contains navigation buttons and an asp panel that will contain the individual wizard panels.
<asp:Panel ID="wizardControlPanel" runat="server">
<!-- Wizard panel goes here -->
</asp:Panel>
<asp:Button ID="backButton" runat="server" Text="< Back" OnClick="BackButton_Click" />
<asp:Button ID="nextButton" runat="server" Text="Next >" OnClick="NextButton_Click" />
<asp:Button ID="cancelButton" runat="server" Text="Cancel" PostBackUrl="~/"/>
One control dynamically fills a checkboxlist
<asp:Label ID="Title" runat="server" Text=""></asp:Label>
<asp:Label ID="DescriptionLabel" runat="server" Text ="Description for the wizard"></asp:Label>
<asp:CheckBoxList ID="ProjectSelector" runat="server" DataTextField="ProjectName" DataValueField="Id" ></asp:CheckBoxList>
I dynamically load this control into my wizardControlPanel once the checkbox is populated.
WizardControl = (BaseWizardControl)LoadControl(("~/Views/" + e.ControlType.Name + ".ascx"));
wizardControlPanel.Controls.Add(WizardControl);
The problem is; on postback I then need to be able to find out which checkboxes were checked server side, but the control no longer exists.
I can't find it on the _page variable. Running in to problems (I think) because I am adding the control to a content holder. How can I get this control back?
It is there, you just won't be able to access it using an ID. You'll need to find it by looking through the wizardControlPanel.Controls collection. I think there is a property that represents the filename you used. But it would be best to use the debugger to track down either where it is in the collection or an identifier you can use to find it.
Having done this once or twice, I think I also remember that you'll need to recreate the control prior to the OnLoad event of the life cycle so that the postback will be able to populate it.
As Markus says, there is probably a better way to do what you are trying to do. But if you MUST load this dynamically, this is how you should go about locating it.
If you add controls dynamically in ASP.NET WebForms, you need to re-add them manually very early in the page lifecycle of the PostBack (e.g. by overriding OnInit and creating the control with the same id in this code) in order to be able to retrieve the values. See this link for a How-To.
The following sample shows the basic steps. It consists of an ASPX-page that contains a Panel as a placeholder:
<asp:Panel ID="wizardPanel" runat="server">
</asp:Panel>
<asp:Button ID="btn" runat="server" Text="Do a postback" />
<br />
<asp:Label ID="lbl" runat="server" />
This is the codebehind-file:
public partial class DynamicUserControls : System.Web.UI.Page
{
protected UserControl userCtrl;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Page.IsPostBack)
CreateUserControl();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
CreateUserControl();
else
{
lbl.Text = "The following values were selected: " + string.Join(", ", ((IGetSelectedValues)userCtrl).SelectedValues);
}
}
private void CreateUserControl()
{
if (Request["UserCtrl"] == "A")
{
userCtrl = (UserControl) LoadControl("~/MyUserControlA.ascx");
userCtrl.ID = "myUserCtrl";
wizardPanel.Controls.Add(userCtrl);
}
else if (Request["UserCtrl"] == "B")
{
userCtrl = (UserControl)LoadControl("~/MyUserControlB.ascx");
userCtrl.ID = "myUserCtrl";
wizardPanel.Controls.Add(userCtrl);
}
}
}
The basic steps are the following:
The page determines the user control type to be created upon a Request parameter during Page_Load (or later if necessary). It assigns the ID myUserCtrl to the UserControl.
Upon a PostBack, the page inspects the Request parameters again and re-creates the UserControl with the same ID myUserCtrl. This is important so that ASP.NET can retrieve the new values of the control from the postback data after the page initialization phase. The hardest part is usually to decide which user controls to create, because the data that are available in OnInit is usually not too many.
In Page_Load, the user control can be accessed and the values that were posted back are available. The UserControls in the sample contain a CheckBoxList and implement an interface that allows to retrieve the values that were selected by the user.
In most cases it is easier to find a different approach. Maybe you can use a MultiView control for your wizard that contains the UserControls for the wizard pages as static content. See this link for a description of how to use the MultiView control. If there are not too many (read unlimited) different UserControls to use, this approach is much more stable.
I was looking in the wrong place. Page.Form as opposed to Page.Request.Form. Due to the fact the checkboxlist is already defined in the user control, it's name is traceable in this variable. This way I can keep the current wizard structure.
In asp.net I have a table in database containing questions,date of submission and answers.On page load only questions appear.now i want to use any link which on clicking show answers and date specified in table data, either in textbox or label and clicking again on that link answer disappear again like expand and shrink on click.
So what coding should i use for this in C#?
I believe you could handle the ItemCommand event of the Repeater.
Place a LinkButton control for the link that you want the user to click in the Repeater's item template. Set the CommandName property of this to something meaningful, like "ShowAnswers". Also, add a Label or TextBox control into the Repeater's item template, but set their Visible property to false within the aspx markup.
In the code-behind, within the ItemCommand event handler check if the value of e.CommandName equals your command ("ShowAnswers"). If so, then find the Label or TextBox controls for the answers and date within that Repeater item (accessed via e.Item). When you find them, set their Visible property to true.
Note: you could take a different approach using AJAX to provide a more seamless experience for the user, but this way is probably simpler to implement initially.
I think the implementation would look something like this. Disclaimer: I haven't tested this code.
Code-Behind:
void Repeater_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "ShowAnswers")
{
Control control;
control = e.Item.FindControl("Answers");
if (control != null)
control.Visible = true;
control = e.Item.FindControl("Date");
if (control != null)
control.Visible = true;
}
}
ASPX Markup:
<asp:Repeater id="Repeater" runat="server" OnItemCommand="Repeater_ItemCommand">
<ItemTemplate>
<asp:LinkButton id="ShowAnswers" runat="server" CommandName="ShowAnswers" />
<asp:Label id="Answers" runat="server" Text='<%# Eval("Answers") %>' Visible="false" />
<asp:Label id="Date" runat="server" Text='<%# Eval("Date") %>' Visible="false" />
</ItemTemplate>
</asp:Repeater>
I'm new to ASP.NET and don't really understand how to display a table with database data. The data is loaded in an object, where I have a list of objects.
Now I want to show a table with some columns, an image (path created from two fields in the object), an link (passing one field of the object), a textarea (id from object, value from object), a radiobutton (id from object).
How should I do this. I have tried binding a datagrid to the list of objects, and it works. But I don't want to show all data members, and I don't know how to create correct headers and the image and form controls.
ImageDataGridView.DataSource = tradeObj.Images;
ImageDataGridView.DataBind();
To stop the automatic creation of a column for each column in the data source, set:
ImageDataGridView.AutoGenerateColumns = false
Then you need to define a column for each column in the data source that you want to display - depending on the column you may want a bound column (you can control the format) or something more involved.
See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datagrid.columns.aspx for a sample and the different column types available
You can spefify your column and header using boundfield
<asp:boundfield datafield="yourColumn"
headertext="theHeaderText"/>
And you need to turn off:
ImageDataGridView.AutoGenerateColumns = false
To format values look at this link at msdn.
You need to use template field to customize your datagrid as per below
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField ShowHeader="True">
<ItemTemplate>
<asp:Image runat="server" ID="Image1"
ImageUrl="Enabled.gif" />
</ItemTemplate>
</asp:TemplateField>
......
......
</Columns>
</asp:GridView>
See this msdn link to work with template field in datagrid
Update
For iterate through every row of gridview you need to handle Rowdatabound event as per below.
protected void gridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Image imgCtrl = (Image) e.Row.FindControl("imgCtrl");
imgCtrl.ImageUrl = "you can apply any format of url here";
}
}
for more information of Rowdatabound event visit this link
Just set autogenerate to false on your datagrid/gridview control. You can then create a templateField column & drop a label or textbox control inside itemTemplate & bind them like
<asp:Label ID="lblMyColumn" Text="<%# Bind("YourColumnName") %>' runat="server"></asp:Label>
Alternatively you can also drop a boundField & set its properties
<asp:BoundField DataField="YourColumnName" HeaderText="Your Text" SortExpression="YourColumnName" />
I have a GridView that displays data on three columns. On the third column I have a CheckBox. I have two things that I need to achieve
CheckBox will be checked based on the column value (1,0)
If it is checked the rest of the two columns should display #### However the data for the two columns should remain in the database.
How can this be achieved?
Can I find the CheckBox on RowDataBound event and check the value and make the CheckBox checked and unchecked? How about making the other columns ####?
NEW Comments:
string str = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[2].ToString();
this helps to set the checkbox checked or not.
if checked is true I am trying the following.
((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[0] = "#####";
((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[1] = "#####";
((System.Data.DataRowView)(e.Row.DataItem)).Row.AcceptChanges();
It is displaying the gridview checkbox as checked but the column value is not changed to "####"
You can turn your item columns into TemplateColumns and do the following which will localize your code to the control level and you don't have to worry about all the searching. I pefer to never use the built in column types because there are usually future enhancements that require changing the columns to TemplateColumns anyways. It also gives you a lot of flexibiltiy on useage.
Here is an example:
<asp:GridView ID="grdYourGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="YourField1">
<ItemTemplate>
<asp:Literal runat="server" ID="ltYourField1"
OnDataBinding="ltYourField1_DataBinding" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="YourField2">
<ItemTemplate>
<asp:Literal runat="server" ID="ltYourField2"
OnDataBinding="ltYourField2_DataBinding" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="YourCheckBoxField">
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkYourCheckBoxField"
OnDataBinding="chkYourCheckBoxField_DataBinding" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in your codebehind implement each control's OnDataBinding:
protected void ltYourField1_DataBinding(object sender, System.EventArgs e)
{
Literal lt = (Literal)(sender);
lt.Text = (bool)(Eval("YourCheckBoxField")) ?
"##########" : Eval("YourField1");
}
protected void ltYourField2_DataBinding(object sender, System.EventArgs e)
{
Literal lt = (Literal)(sender);
lt.Text = (bool)(Eval("YourCheckBoxField")) ?
"##########" : Eval("YourField2");
}
protected void chkYourCheckBoxField_DataBinding(object sender, System.EventArgs e)
{
CheckBox chk = (CheckBox)(sender);
chk.Checked = (bool)(Eval("YourCheckBoxField"));
}
The advantages to doing it this way is your could replace code easily as it is all isolated and has no 'searching' for expected controls. I very rarely use the RowDataBound event because it makes you have to write specific code to look for the controls and it makes more sense to me to have the code localized to the control. If someone changes something they know there are ONLY affecting that one control instead of everything on the row possibly as a side effect. You could also use the <%# method and do the Evals right in the markup but I personally prefer to never have any code in the aspx markup at all.
I have got a grid[Grid1] that build its dataRows when a button[search] is clicked, I managed to Ajaxify it by placing it in an UpdatePanel and it worked fine. Before Ajaxifying Grid 1, another grid[Grid2] and some other controls[Text and Labels] used to get populated/updated when a row in Grid 1 was clicked .
The Grid2 and other controls used to get populated/updated on the OnItemCommand Event of Grid 1.Its the code in the OnItemCommand that binds the related data to Grid2 and other controls.
After I placed the Grid 1 in the update panel,they stopped updating. It will work fine if I place Grid2 and other controls in the same Update Panel but the page is designed in a way that I cant have those controls in the same UpdatePanel as the first Grid nor I dont intend to use another Update Panel.
I hope I'm making some sense. I'm a newbie in .Net so please excuse. Please find the code below.
<asp:ScriptManager EnablePartialRendering="true" ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers ="True">
<ContentTemplate>
<asp:DataGrid ID="grdJobs" runat="server" AllowPaging="true"
AlternatingItemStyle-CssClass="gridAltItemStyle"
AutoGenerateColumns="False" CellPadding="0"
DataKeyField="code"
CssClass="datagridBox"
GridLines="horizontal"
PagerStyle-Mode="NumericPages"
HeaderStyle-CssClass="gridHeaderStyle"
ItemStyle-CssClass="gridItemStyle"
PagerStyle-CssClass="gridPagerStyle"
Width="445px" OnPageIndexChanged="grdJobs_PageIndexChanged" OnItemCreated="grdJobs_ItemCreated" OnItemCommand="grdJobs_ItemCommand" OnItemDataBound="grdJobs_ItemDataBound">
<Columns>
<asp:BoundColumn DataField="J_ID" HeaderText="Job"></asp:BoundColumn>
<asp:BoundColumn DataField="Contract" HeaderText="Contract" ReadOnly="True"></asp:BoundColumn>
<asp:BoundColumn DataField="J_Fault_Line1" HeaderText="Fault" ReadOnly="True"></asp:BoundColumn>
<asp:BoundColumn DataField="j_p_id" HeaderText="Fault" Visible="false" ></asp:BoundColumn>
<asp:ButtonColumn Text="<img src=images/addFeedback.gif style=border: 0px; alt=Add Feedback>" ButtonType="LinkButton" HeaderText="Add" CommandName="Load" ItemStyle-cssClass="Col_9_Item_2"></asp:ButtonColumn>
</Columns>
</asp:DataGrid>
<asp:ImageButton ID="cmdLkp" ImageUrl="Images/search.gif" runat="server" OnClick="cmdLkp_Click" />
</ContentTemplate>
</asp:UpdatePanel>
The code below in the code behind stopped working
protected void grdJobs_ItemCommand(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Load")
{
functionToBindDataToGrid2();
functionToBindDataToOtherControls();
}
}
protected void grdJobs_ItemDataBound(object sender, DataGridItemEventArgs e)
{
e.Item.Attributes.Add("onclick", "javascript:__doPostBack('grdJobs$ctl" + ((Convert.ToInt32(e.Item.ItemIndex + 3).ToString("00"))) + "$ctl00','')");
}
In the properties for the UpdatePanel, set the update mode to "Conditional" and ChildrenAsTriggers to "true".
Another option would be to move the button inside the update panel so that you wouldn't have to have the trigger.
A GridView is a complex asp.net server control. You will have a lot of difficulty updating Grid2 after Grid1 is updated inside of the UpdatePanel. However, it is possible to a execute JavaScript on the client after Grid1 is updated. You could update Grid1 inside of the update panel, execute JavaScript after Grid1 has been updated that will update HTML on the page. The problem is that updating Grid2 with Javascript is going to be a nightmare amount of work.
Here's an example of what I'm talking about: Ajax Enabled Gridview using JavaScript in ASP.NET. It is a total hack, a huge amount of work, and your co-workers will hate you when they have to maintain it.
If you wanted to update a label or a dropdown list then that would be possible but updating a GridView using Javascript and having those updates persist across postbacks is a daunting challenge.
Use multiple UpdatePanels on one page. It won't affect the layout.
You can then use triggers (for the panels) in order to affect which controls you want affected.
Here's a page that will help you understand.
http://www.asp.net/ajax/tutorials/understanding-asp-net-ajax-updatepanel-triggers
Your problem is down to the way you are triggering the postback on row click, i.e.: this method
protected void grdJobs_ItemDataBound(object sender, DataGridItemEventArgs e)
{
e.Item.Attributes.Add("onclick", "javascript:__doPostBack('grdJobs$ctl" + ((Convert.ToInt32(e.Item.ItemIndex + 3).ToString("00"))) + "$ctl00','')");
}
Manually writing the __doPostBack script is generally always a bad idea. I believe what you need to use instead is ClientScriptManager.GetPostBackEventReference which will create a similar looking postback script for you, but will take into account all sorts of other things including AJAX-ification of the control.
Try something like this instead:
protected void grdJobs_ItemDataBound(object sender, DataGridItemEventArgs e)
{
e.Item.Attributes.Add("onclick", ClientScriptManager.GetPostBackEventReference(e.Item, string.Empty);
}