Getting the bound type of templated column controls in gridView - asp.net

Hi I have following grid view
<asp:GridView ID="grdSettings" runat="server" Height="400px" Width="100%"
AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField HeaderText="XYZ" BoundFieldName="XYZTypeName">
<ItemTemplate>
<asp:Label ID="lblCustomerName" runat="server" Text='<%# Bind("CustomerName") %>'>
</asp:Label>
<asp:Label ID="lblCostumerId" runat="server" Text='<%#Bind("CustomerId") %>'></asp:Label>
</asp:TemplateField>
</Columns>
</asp:GridView>
Which is bound by List of Customer ,class is as follows
Class Customer
{
public string CustomerName { get; set; }
public int CustomerId { get; set; }
}
Now on a method named GetGridStuff() , i need to iterate in every column and get the type that was bound to controls in template field. For example in case of the first control in the template field
<asp:Label ID="lblCustomerName" runat="server" Text='<%# Bind("CustomerName") %>' >
</asp:Label>
I need to know what type of property data it contains , in this case its CustomerName. I need to get this dynamically at run time as to write code in part of program which is not aware if this grid structure. I have the grid object with me and i can access all properties.

Let me try this, being away from coding for more than 5 years now and if I understand the problem correctly as you may want to handle it through server side code.
Look for an event called ItemBound (or similar forgive me for my memory), this gives you values of all the items in current row (Properties). You also need to declare temp control types (label,textbox etc) and assign corresponding value to these controls using e.FindControl with appropriate type casting, e.g. Label l = (Label)e.Findcontrol("Name")
downside of the approach you should avoid too much of process as it is going to execute on every row creating of the grid.
Let me know if you still want a precise code to handle the problem but otherwise this description should at least help you to look for Row Level Event to crack the prob and also encourage you to stick to tech forums :)

Related

How to bind part of form values to model in asp.net webform

I inherited an asp.net webform application. Now when I try to add new feature to it. I hit the following stop:
I created a form to get data from end user, and the data goes into two tables in the database.
I used Entity Framework to deal with communication with database.
My question is, because the form data need to go into two models(two tables), can I bind one model to part of the form data?
Or there is no way to do that, I have to go through each and every form data and assign them to the model properties?
for example
data model would be
class ModelA{
public int ModelAID {get;set;}
public string ModelAName {get;set;}
}
class ModelB{
public int ModelBID {get;set;}
public string ModelBName{get;set;}
}
front end page would be
<form>
<input name="Aid"/>
<input name="AName"/>
<input name="Bid"/>
<input name="BName"/>
</form>
code behide would be
What kind of version are you using?
I'm developing in web forms 4.5, and I have suffered with the similar problem.
The short answer is.. kinda difficult but you can do it with some restrictions.
For data binding, I'm not sure what you mean..
if you want to just bring the data, or you want to update and delete the data as well.
For me, I am using gridview everywhere to show the data and also to update, delete it, and in my experience, updating and delete is possible for one table.
But you could show other table's data by showing it in ItemTemplate.
Here is a short example of what i did :
<asp:GridView runat="server" ItemType="model"
ID="someGrid" SelectMethod="someGrid_GetData" CellPadding ="10"
autoGenerateColumns="false" deleteMethod="someGrid_DeleteItem"
updateMethod="someGrid_UpdateItem" DataKeyNames="id"
AutoGenerateDeleteButton="true" AutoGenerateEditButton="true">
<Columns>
<asp:DynamicField DataField="col1" />
<asp:BoundField DataField="col2" HeaderText="col2" />
<asp:TemplateField HeaderText="details">
<ItemTemplate>
<asp:HyperLink ID="detailLink" runat="server" Text="details" NavigateUrl='<%# "~/someDetails?some=" + Eval("someDetails") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="vendor">
<ItemTemplate>
<asp:Label ID="vendorLbl" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
as you can see, you could update, delete the data from model table, but you can also put data inside vendor as a label from the code behind.
I've spent many time figuring about this.
And hope this helps!

asp.net gridview bind dateformat not working with update

I have a GridView with a TemplateField column which shows a DateTime from a DataSource.
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="Start Date">
<EditItemTemplate>
<asp:TextBox ID="txtDateStart" runat="server"
Text='<%# Bind("dtDateStart", "{0:dd/MM/yyyy}") %>'</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("dtDateStart", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Displaying the date in the correct format works as it should. Note that the format starts with DAY followed by MONTH.
When I switch to edit mode, change the date in the TextBox to '31-01-2013' and press the GridView's update-link i get an error:
Cannot convert value of parameter 'dtDateStart' from 'System.String' to 'System.DateTime'
The error is generated by the GridView not my own code.
It happens before the UpdateMethod of my DataSource is called.
When i type '01-31-2012' the data is processed correctly and the value is updated into the database.
Somehow when the date is displayed it uses format dd-MM-yyyy (just as I need it to)
But when it reads the new value form the TextBox it uses MM-dd-yyyy
Can somebody please help me?
thanks for your reply.
I do not know about culture settings within the website. I was assuming that proving the Bind-function with a dateformat would be sufficient.
By now I have implemented the following workaround, which is hopefully useful for others:
I have added an additional property to my class which is of type string. This property I only use for binding to the gridview.
// Original Date property //
public DateTime dtDateStart { get; set; }
// Additional Date property of type string //
public string sDateStart
{
get
{
return dtDateStart.ToString("dd/MM/yyyy");
}
set
{
dtDateStart = DateTime.ParseExact(value, "dd/MM/yyyy", null);
}
}
I am not sure if this should be marked as the answer. But maybe others can use this as a quick workaround as well.
I think you can use like this
<EditItemTemplate>
<asp:TextBox ID="txtDateStart" runat="server"
Text='<%# Convert.ToDateTime(Bind("dtDateStart")).ToString("dd/MM/yyyy") %>'</asp:TextBox>
</EditItemTemplate>
this weill help you.

ASP literal inside a repeater footer template

I think this is not possible by trying to add a literal into a footer template of a repeater so that I can fill it later on...
<FooterTemplate>
<asp:Literal ID="panelFooter" runat="server"></asp:Literal>
</FooterTemplate>
You can data bind the Text attribute to the result of a method in your code-behind. In this example we are going to display the total number of products in the footer:
<FooterTemplate>
Total number of products:
<asp:Literal runat="server" Text='<%# GetTotalNumberOfProducts() %>' />
</FooterTemplate>
In the code-behind we are going to create a method that calculates the number and returns it for the Literal control.
protected string GetTotalNumberOfProducts()
{
return 42.ToString();
}
Notice that we don't need to find the control by its ID. We are just returning s string and the data binding syntax will call our method in code-behind and put the result inside the control.

Eval() in ASP. How to pass values on redirect

<asp:GridView ID="GridView1" runat="server" CssClass="style29">
<Columns>
<asp:TemplateField HeaderText="Send Message to Group">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl='SendMessage.aspx?GroupName=<%# Eval("GroupName") %>' Text='Send Message'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am redirecting the to SendMessage.ASPX page which has a text box, I have to pass the group name to that text box. Please help me guys I am new to programming. It gets redirected but how to pass that value to this text box below in SendMessage.aspx page.
Sorry I may have misunderstood your question, however the common pattern involves the query string
You can access the query string values as
if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["GroupID"]) == false) {
String groupId = HttpContext.Current.Request.QueryString["GroupID"];
}
you would then be able to set this value to the textbox.Text property in your page load event, which will apply the value from the query string to the textbox.
Generally, you want to check for null or empty strings before attempting to access the query string.
Also, always remember that this kind of action is often a target for malicious users to do malicous things with your website, so you must check inputs to ensure 'bad' inputs are ignored.

How to modify Bind("MyValue") in asp.net

I'm having headache with Time values and multiple time zones.
I'm storing new DateTime values in UTC time, but I face problem when I try to modify them using LinqDataSource and GridView.
I can easily show correct time in
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# TimeManager.ToLocalTime((DateTime)Eval("OrderDate")) %>' />
</ItemTemplate>
Currently this will add 1 hour to UTC time stored in DB.
However, binding back to source is not easy. Bind("OrderDate") cannot be modified like TimeManager.ToGlobalTime((DateTime)Bind("OrderDate")).
I was thinking of using OnUpdating event of LinqDataSource to update value to global time, but what if user modified other fields and not date field? Every time he updates record time value would be smaller for one hour.
Comparing old and new values also is not great because user can modify date portion of datetime and not time, which is influenced by time zones?
If I had way to show local time in gridview's all states then I could easily use OnUpdating of LinqDataSource.
Please share your thoughts...
Have you considered making the change to your model? Let's assume that the name of the object you are binding to is CustomerOrder. You could add the following class to your project (in the same namespace as your Linq objects):
public partial class CustomerOrder
{
public DateTime LocalOrderDate
{
get { return TimeManager.ToLocalTime(OrderDate); }
set { OrderDate = TimeManager.ToUTCTime(value); }
}
}
Now instead of binding to OrderDate, bind to LocalOrderDate. This will automatically make the UTC / Local Time conversion to the OrderDate.
(Note: I'm assuming you have TimeManager.ToLocalTime() and TimeManager. ToUTCTime() properly defined)
The way I've handled this sort of thing in the past is to use Eval in the EditItemTemplate as well. Let the user edit the item in local time. Then add OnItemUpdating handler for the gridview and add extract the value of the associated text box, convert it to global time, and add that to the new values dictionary. Bind the original value in (in global time) to a hidden field in the same template, which will populate the old values dictionary with the correct old time. You'll want to do the same thing on insertion in OnItemInserting although you obviously don't need the old value (since there isn't one).
EDIT: Usually I do my updates on a DetailsView not a GridView, thus the ItemUpdating/Inserting instead of RowUpdating/Inserting. Sample code below -- this example uses a pair of dropdown lists that allows the user to specific a location (choose a building and a location in the building, but it actually only maps the location in the database). On the back end it assigns initial values to the dropdowns in OnPreRender (not shown) and extracts the LocationID database field value from the location dropdown on ItemUpdating/Inserting (updating shown). The DetailsView is wrapped in an UpdatePanel and the population of the Location dropdown is done when the building dropdown selection changes. Note that since I'm updating the item (causing an update statement anyway) I don't care if the LocationID field gets overwritten on the update with the same value so I don't bother to keep the old value on the page.
<asp:TemplateField HeaderText="Location:" SortExpression="LocationId">
<EditItemTemplate>
<asp:DropDownList runat="server" ID="buildingDropDownList"
DataSourceID="buildingDataSource"
DataTextField="name"
DataValueField="abbreviation"
OnSelectedIndexChanged=
"buildingDropDownList_SelectedIndexChanged"
AutoPostBack="true" />
<asp:DropDownList runat="server" ID="locationDropDownList"
DataSourceID="locationsDataSource"
DataTextField="Name"
DataValueField="ID">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList runat="server" ID="buildingDropDownList"
DataSourceID="buildingDataSource"
DataTextField="name"
DataValueField="abbreviation"
OnSelectedIndexChanged=
"buildingDropDownList_SelectedIndexChanged"
AutoPostBack="true"
AppendDataBoundItems="true">
<asp:ListItem Text="Select Building" Value="" />
</asp:DropDownList>
<asp:DropDownList runat="server" ID="locationDropDownList"
DataSourceID="locationsDataSource"
DataTextField="Name"
DataValueField="ID"
AppendDataBoundItems="true">
<asp:ListItem Text="Not installed" Value="" />
</asp:DropDownList>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="locationLabel" runat="server"\
Text='<%# Eval("LocationID") == null
? ""
: Eval("Location.Name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Codebehind:
void editPrinterDetailsView_ItemUpdating( object sender,
DetailsViewUpdateEventArgs e )
{
// Use a helper method to find the dropdown inside the details view
// and get the selected value.
string locationID = ControlHelper
.GetDropDownValue( editPrinterDetailsView,
"locationDropDownList" );
if (locationID == string.Empty)
{
locationID = null;
}
if (e.NewValues.Contains( "LocationID" ))
{
e.NewValues["LocationID"] = locationID;
}
else
{
e.NewValues.Add( "LocationID", locationID );
}
e.OldValues["LocationID"] = -1;
}

Resources