RadGrid - Multiple Controls in same column in edit template in Batch Edit - asp.net

I am using batch editing in a radgrid with save button outside the grid. In side grid there are template columns and their edit templates have multiple values. I am able to assign values to them. But when I click on save in side bath edit command method the corresponding key of newvalues gives value of [object object]
<telerik:GridTemplateColumn HeaderText="Dwg Sch" ColumnGroupName="WACompOrderEntry" UniqueName="DwgSchedule" HeaderTooltip="This is the date the factory has promised to provide approval drawings to the field (loaded automatically from Vista when available)">
<ItemTemplate>
<asp:Label runat="server" ID="lblRdDwgSch" Text='<%# Eval("Vista_Sub", "{0:M/d/yy}") %>' ToolTip="This is the date the factory has promised to provide approval drawings to the field (loaded automatically from Vista when available)"></asp:Label>
<br />
<asp:Label ID="lblDwgSch" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadDatePicker ID="rdDwgSch" runat="server" Width="80px" DbSelectedDate='<%# Eval("Vista_Sub", "{0:M/d/yy}") %>' ToolTip="This is the date the factory has promised to provide approval drawings to the field (loaded automatically from Vista when available)"></telerik:RadDatePicker>
<asp:TextBox ID="txtDwgSch" runat="server" Width="80px" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
Above is the template column definition
protected void gridMilestoneMatrixEntry_BatchEditCommand(object sender, GridBatchEditingEventArgs e)
{
if (e.Commands == null)
{
return;
}
Cache.Remove("MileStoneData");
var updatedCommands = e.Commands.Where(x => x.Type == GridBatchEditingCommandType.Update);
var deletedCommands = e.Commands.Where(x => x.Type == GridBatchEditingCommandType.Delete);
List<int> updatedRecords = new List<int>();
List<long> deletedRecords = new List<long>();
if (updatedCommands != null && updatedCommands.Count() > 0)
{
updatedRecords = UpdateMilestoneMatrix(updatedCommands.ToList());
}
Now inside the hashtable key values do not give values for object
updatedValues["DwgSchedule"] it gives value as [object object]
if (updatedValues["DwgSchedule"] != null)
{
tempStr = updatedValues["DwgSchedule"].ToString();
if (!string.IsNullOrEmpty(tempStr))
{
confDwgExp = DateTime.ParseExact(updatedValues["DwgSchedule"].ToString(), "M/d/yyyy", CultureInfo.InvariantCulture);
}
tempStr = string.Empty;
}

The way I decided to go about doing these things was to have the iterate through the rows of the grid by using the RadGrid.Items
This allows you to access each individual row, which in essence gives you access to the row's individual controls (i.e not just the cells, but everything on the row).
Private Sub RbtnSaveAll_Click(sender As Object, e As EventArgs) Handles RbtnSaveAll.Click
For Each item As GridDataItem In grdActivities.Items 'Iterates over the rows
'Get your controls by using item.findcontrol("controlname").
'Then send the data of the changed controls to the datasource
Next
bindGrid(True) 'Do your bind event if necessary
End Sub
If you want a c# version you can simply convert it using telerik's converter
EDIT:
<asp:Button ID="btnBulkBookOn" runat="server" Text="Book On" CommandName="Update"/>
VB-code:
Private Sub radgrdResources_UpdateCommand(sender As Object, e As GridCommandEventArgs) Handles radgrdResources.UpdateCommand
' This will be invoked when you clikc the button and fire off the Radgrid's native save.
End Sub

Related

'System.String' does not contain a property

<asp:Repeater ID="rptProducts1" runat="server">
<ItemTemplate>
<div class="product_header">
<asp:Label ID="prodLabels" runat="server" >
<p><h4><%#Eval("Name") %></h4></p>
</asp:Label>
</div>
<div class="left-col">
<div class="img_product">
<asp:Image ID="imgProduct" runat="server" ImageUrl='<%# Eval("Picture") %>' Width="200px" Height="200px"/>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
List<ProductModel> _prodObj = new List<ProductModel>();
_prodObj = response.Content.ReadAsAsync<List<ProductModel>>().Result;
_prodObj.Where(x => x.PictureId != 0).Select(v => v.Picture = "data:image/png;base64," + Convert.ToBase64String(v.PictureBinary));
var _prodname = _prodObj.Where(x=>x.Id!=0).Select(i => i.Name=""+i.Name);
try
{
rptProducts1.DataSource = _prodname;
rptProducts1.DataBind();
}
catch (Exception ex)
{
throw;
}
Issue while fetching data from the database.Want to display name and image of the product.While fetching records 'System.String' does not contain a property error is thrown.
Thanks in advance.
You are databinding your repeater to a list of String as far as I can see.
This line will fetch a list of strings:
var _prodname = _prodObj.Where(x=>x.Id!=0).Select(i => i.Name=""+i.Name);
=> _prodname will be equal to a list of names.
And then, when you databind, you have this line:
Eval("Id")
Which is essentially saying: take the current object (which is a String) and print the Id property here. But since it's a String, it has no ID property, hence your exception.
So in short: bind to the list of products you want to display (the full objects, not just the names), or change your view to not use any properties that simply aren't there.
UPDATE
If you just want to display the one product, I'd advise you to select the right product server-side before databinding your control, like this for instance:
var _prodname = _prodObj.Where(x=>x.Id!=0 && x.Id == myId).FirstOrDefault().Select(i => i.Name=""+i.Name);
... where "myId" is of course the Id you're searching for.
And then, you should use a repeater to show the data. You can just use a Label like this:
<asp:Label ID="myLabel" runat="server" />
// and server side you would do this:
myLabel.Text = _prodName;
prodObj.Where(x=>x.Id!=0)
I suspect this is failing because x is a string and not what you expect it to be.
You need to do some debugging to identify what type x is, and then trace back to find where it stops being what you expect it to be.
Also,
_prodObj.Where(x => x.PictureId != 0).Select(v => v.Picture = "data:image/png;base64," + Convert.ToBase64String(v.PictureBinary));
LINQ is evaluated lazily, unless something enumerates the result of the above expression nothing will be executed.

Hide / unhide Label, textbox depending on the db results in asp.net

I need to hide /unhide the labels and textbox depending on db results , I tried something like this but it doesnt works, the condition should be like if the db field is empty for that field , then the label associated with that field should hidden (not visible) , following is the code i tried :
<asp:Label ID="lblBirth" Text="DOB:" runat="server" ViewStateMode="Disabled" CssClass="lbl" />
<asp:Label ID="DOB" runat="server" CssClass="lblResult" Visible='<%# Eval("Berth") == DBNull.Value %>'></asp:Label>
Code behind:
protected void showDetails(int makeID)
{// get all the details of the selected caravan and populate the empty fields
DataTable dt = new DataTable();
DataTableReader dtr = caravans.GetCaravanDetailsByMakeID(makeID);
while (dtr.Read())
{
//spec
string value = dtr["Price"].ToString();
lblModel.Text = dtr["model"].ToString();
birthResult.Text = dtr["Berth"].ToString(); }}
To make your aspx version work your control should be data bound to data source that contains "Berth" property. As I can see from code behind, you prefer to use c# to populate controls. In this case you may just do the following:
DOB.Visible = dtr["Berth"] == DBNull.Value;
I think that using data binding is more preferable solution.

Converting client side html radio buttons to asp.net web controls with dynamic ids. (ASP.net)(VB)

I have the following client side code in .aspx page within a datalist itemtemplate that takes questions from the database like this:
<Itemtemplate>
<b> <%=GetQuestionNum()%>)
<%#Server.HtmlEncode(Eval("Text").ToString())%></b>
<br />
<asp:Panel ID="A" runat="server" Visible='<%#GetVisible(Eval("OptionA").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="A">
<%#Server.HtmlEncode(Eval("OptionA").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="B" runat="server" Visible='<%#GetVisible(Eval("OptionB").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="B">
<%#Server.HtmlEncode(Eval("OptionB").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="C" runat="server" Visible='<%#GetVisible(Eval("OptionC").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="C">
<%#Server.HtmlEncode(Eval("OptionC").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="D" runat="server" Visible='<%#GetVisible(Eval("OptionD").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="D">
<%#Server.HtmlEncode(Eval("OptionD").ToString())%>
</option><br />
</asp:Panel></itemtemplate>
The output is like:
1) What is your age group?
- Option 1
- Option 2
- Option 3
- Option 4
The ID's of the radio buttons are dynamic ("Q" & QuestionID). If there is no answer to a question then the GetVisible function returns false and the containing panel is hidden.
I have been trying to get rid of the html and replace these with asp:radiobuttons but it is not possible to set id's from databinding.. only simply. I was trying something like:
<asp:RadioButton ID="Q<%#Eval("ID")%>" runat="server" Visible='<%#GetVisible(Eval("OptionA").Tostring())%>'
Text='<%#Server.HtmlEncode(Eval("OptionA").ToString())%>' />
Here is the function that provides data:
Public Shared Function GetQuestionsForSurvey(ByVal id As Integer) As DataSet
Dim dsQuestions As DataSet = New DataSet()
Try
Using mConnection As New SqlConnection(Config.ConnectionString)
Dim mCommand As SqlCommand = New SqlCommand("sprocQuestionSelectList", mConnection)
mCommand.CommandType = CommandType.StoredProcedure
Dim myDataAdapter As SqlDataAdapter = New SqlDataAdapter()
myDataAdapter.SelectCommand = mCommand
mCommand.CommandType = CommandType.StoredProcedure
mCommand.Parameters.AddWithValue("#id", id)
myDataAdapter.Fill(dsQuestions)
mConnection.Close()
Return dsQuestions
End Using
Catch ex As Exception
Throw
End Try
End Function
but I'm finding it impossible to work with the html controls, i.e get their .text value from codebehind, or adding events!
Please can an expert suggest a better way to replace the html with suitable asp.net web controls or from the codebehind and output it. Or point me in the right direction?
Thanks :0)
I had some experience with ASP controls and data binding. The problem you are facing is probably the fact that once you declare a control via markup you can't access it from data binding. Also, you should not confuse the server-side ID with the client-side ID.
The server-side ID, mapped to Id property of controls, is used to programmatically access the control from code behind. Client-side ID is the ID that will be placed in tag's id attribute and is mapped to ClientId property.
Judging from your question, what you need is to build a multi-choice survey, and, in my opinion, it's not important how the IDs are generated, just that they are properly grouped for each question.
I'll answer the part of programmatically accessing controls in data binding, which is a part of your question.
Here is an example from my code. Suppose you have a very simple GridView like this
<asp:GridView ID="example" runat="server" OnRowDataBound="DataBound">
<Columns>
<asp:TemplateField HeaderText="New">
<ItemTemplate>
<asp:Image ID="imgExample" runat="server" />
</ItemTemplate>
</Columns>
</asp:GridView>
It takes a data set during data binding and sets the image according to some property. It works the same as DataList, don't worry.
Now, in code behind, you handle the RowDataBoundEvent. You can't access the imgExample object directly, because it's a child of the ItemTemplate. When the row is bound, you have direct access to the row and then you can use the FindControl method of Control class
Here is C# code example (easy to convert to VB)
protected void DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //Required
{
GridViewRow row = e.Row;
[...] //get an email message
(row.Cells[0].FindControl("imgExample") as Image).ImageUrl = (email.AlreadyRead)
? "Mail_Small.png"
: "Mail_New_Small.png";
}
}
Application to your case
In order to build a multi-choice survey, my advice is to create a DataList that will hold questions (the outer control) and then, for each row, declare a RadioButtonList that holds answers (the inner control). Bind the outer data list to the data set of questions and answers. Handle the RowDataBound event or whatever it's called in the DataList world. When you handle that event, bind the inner radiobuttonlist to the answers.
It should work for you
I am actually working on something similar at the moment. I am using javascript and jQuery to dynamically add controls to my page. After adding them to my page I have to get the new controls, their text, etc. The way I've been doing it is something like this:
<table id='BuilderTable' class="BuilderTable">
<tbody class='BuilderBody'>
</tbody>
</table>
<asp:Button runat="server" ID="saveButton" OnClick="SaveButton_Click" OnClientClick="SaveData()"
Text="Save Form" />
<asp:HiddenField runat="server" ID="controlsData" />
This table is where I put all my new controls.
Then when the client clicks the save button it first calls this javascript / jQuery function:
function SaveData() {
var controlRows = $('#BuilderTable tr.control');
var controls= [];
controlRows.each(function (index) {
//process control information here ...
controlText = //use jQuery to get text, etc...
var control = {
Index: (index + 1),
Text: controlText
};
controls.push(control);
});
var str = JSON.stringify(questions);
$('#<%= controlsData.ClientID %>').val(str);
}
Then the server side function for the button click is called (this in in C#, adapt to VB).
protected void SaveButton_Click(object sender, EventArgs e)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
string str = controlsData.Value;
List<Control> controls = jss.Deserialize<List<Control>>(str);
}
Using a Control class like this:
public class Control
{
public int Index { get; set; }
public string Text { get; set; }
}
This code uses javascript and jQuery to get your controls, JSON to serialize the data and save it in a asp hiddenfield then grab the data server-side and deserialize into objects that your code can use. Then take the data and do whatever you need to.

AutoCompleteExtender control in a repeater

I have an AutoCompleteExtender AjaxControlToolkit control inside a repeater and need to get a name and a value from the web service. The auto complete field needs to store the name and there is a hidden field that needs to store the value. When trying to do this outside of a repeater I normally have the event OnClientItemSelected call a javascript function similiar to
function GetItemId(source, eventArgs)
{
document.getElementById('<%= ddItemId.ClientID %>').value = eventArgs.get_value();
}
However since the value needs to be stored in a control in a repeater I need some other way for the javascript function to "get at" the component to store the value.
I've got some JavaScript that might help you. My ASP.Net AutoComplete extender is not in a repeater, but I've modified that code to detect the ID of the TextBox you are going to write the erturned ID to, it should work (but I haven't tested it all the way through to post back).
Use the value from 'source' parameter in the client side ItemSelected method. That is the ID of the calling AutoComplete extender. Just make sure that you assign an ID the hidden TextBox in the Repeater Item that is similar to the ID of the extender.
Something like this:
<asp:Repeater ID="RepeaterCompareItems" runat="server">
<ItemTemplate>
<ajaxToolkit:AutoCompleteExtender runat="server"
ID="ACE_Item"
TargetControlID="ACE_Item_Input"
...other properties...
OnClientItemSelected="ACEUpdate_RepeaterItems" />
<asp:TextBox ID="ACE_Item_Input" runat="server" />
<asp:TextBox ID="ACE_Item_IDValue" runat="server" style="display: none;" />
</ItemTemplate>
</asp:Repeater>
Then the JS method would look like this:
function ACEUpdate_CustomerEmail(source, eventArgs) {
UpdateTextBox = document.getElementById(source.get_id() + '_IDValue');
//alert('debug = ' + UserIDTextBox);
UpdateTextBox.value = eventArgs.get_value();
//alert('customer id = ' + UpdateTextBox.value);
}
There are extra alert method calls that you can uncomment for testing and remove for production. In a simple and incomplete test page, I got IDs that looked like this: RepeaterCompareItems_ctl06_ACE_Item_IDValue (for the text box to store the value) and RepeaterCompareItems_ctl07_ACE_Item (for the AC Extender) - yours may be a little different, but it looks practical.
Good Luck.
If I understand the problem correctly, you should be able to do what you normally do, but instead of embeding the ClientId, use the 'source' argument. That should allow you to get access to the control you want to update.
Since you are using a Repeater I suggest wiring the OnItemDataBound function...
<asp:Repeater id="rptResults" OnItemDataBound="FormatResults" runat="server">
<ItemTemplate>
<asp:PlaceHolder id="phResults" runat="server" />
</ItemTemplate>
</asp:Repeater>
Then in the code behind use something like
`Private Sub FormatResults(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
Dim dr As DataRow = CType(CType(e.Item.DataItem, DataRowView).Row, DataRow) 'gives you access to all the data being bound to the row ex. dr("ID").ToString
Dim ph As PlaceHolder = CType(e.Item.FindControl("phResults"), PlaceHolder)
' programmatically create AutoCompleteExtender && set properties
' programmatically create button that fires desired JavaScript
' use "ph.Controls.Add(ctrl) to add controls to PlaceHolder
End Sub`
Voila

Getting an object back from my GridView rows

Basically, i want my object back...
I have an Email object.
public class Email{
public string emailAddress;
public bool primary;
public int contactPoint;
public int databasePrimaryKey;
public Email(){}
}
In my usercontrol, i a list of Email objects.
public List<Email> EmailCollection;
And i'm binding this to a GridView inside my usercontrol.
if(this.EmailCollection.Count > 0){
this.GridView1.DataSource = EmailCollection;
this.GridView1.DataBind();
}
It would be really awesome, if i could get an Email object back out of the GridView later.
How do i do this?
I'm also binding only some of the Email object's properties to the GridView as well and they're put into Item Templates.
<Columns>
<asp:TemplateField HeaderText="Email Address">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text=<%# Eval("EmailAddress") %> Width=250px />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Primary">
<ItemTemplate>
<asp:CheckBox runat="server" Checked=<%# Eval("PrimaryEmail") %> />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact Point">
<ItemTemplate>
<CRM:QualDropDown runat="server" Type=ContactPoint InitialValue=<%# Eval("ContactPoint") %> />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Can GridView even do this? Do i need to roll my own thing? It'd be really cool if it would do it for me.
To elaborate more.
I am saving the List collection into the viewstate.
What I'm eventually trying to get to, is there will be a Save button somewhere in the control, which when the event fires I'd like to create an Email object from a datarow in the GridView which to compare to my original List collection. Then if there's a change, then I'd update that row in the database. I was thinking that if I could put a List collection into a GridView, then perhaps I could get it right back out.
Perhaps I create a new constructor for my Email object which takes a DataRow? But then there's a lot of complexities that goes into that...
ASP.NET Databinding is a one-way operation in terms of object manipulation. However, the DataSource property will contain a reference to your EmailCollection throughout the response:
EmailCollection col = (EmailCollection)this.GridView1.DataSource;
But I have a feeling that what you really want is a control that manipulates your EmailCollection based on user input and retrieve it in the next request. Not even webforms can fake that kind of statefulness out of the box.
Well I ended up looping through my List EmailCollection, which was saved into the ViewState.
So in the page, a Save button is clicked, when the event is caught, I loop through my List Collection and grab the row from the GridView by index.
On the GridViewRow I have to use a GridView1.Rows[i].Cells[j].FindControl("myControl1") then get the appropriate value from it, be it a check box, text box, or drop down list.
I do see that a GridViewRow object has a DataItem property, which contains my Email object, but it's only available during the RowBound phase.
Unfortunately If/When i need to expand upon this Email Collection later, by adding or removing columns, it'll take a few steps.
protected void SaveButton_OnClick(object sender, EventArgs e){
for (int i = 0; i < this.EmailCollection.Count; i++)
{
Email email = this.EmailCollection[i];
GridViewRow row = this.GridView1.Rows[i];
string gv_emailAddress = ((TextBox)row.Cells[0].FindControl("EmailAddress")).Text;
if (email.EmailAddress != gv_emailAddress)
{
email.EmailAddress = gv_emailAddress;
email.Updated = true;
}
...
}
}
I'd still be open to more efficient solutions.
Just a thought, basically a roll your own but not that tricky to do:
Store the list that you use as a datasource in the viewstate or session, and have a hidden field in the gridview be the index or a key to the object that matches the row.
In other words, each row in the gridview "knows" which email object in the list that it is based on.
If you want to hold onto an object like this its easiest to use the viewstate, although you will be duplicating the data but for a small object it should be ok.
ViewState.Add("EmailObj", Email);
EMail email = (Email)ViewState["EmailObj"];

Resources