RadComboBox with checkboxes in Radgrid - select values from the table - telerik

I have a RadComboBox with checkboxes in Radgrid. User is able to select multiple values and data is saved into database. The problem I am having is, how to display already selected values when pulling data from database.
<telerik:RadGrid RenderMode="Lightweight" AutoGenerateColumns="false" ID="grd_incontact_settings" BorderWidth="0" Font-Size="Smaller" Width="100%" ShowFooter="True" AllowPaging="True" runat="server" PageSize="250" PagerStyle-AlwaysVisible="true"
OnNeedDataSource="grd_incontact_settings_NeedDataSource" AllowAutomaticInserts="True" OnInsertCommand="grd_incontact_settings_InsertCommand">
<GroupingSettings CaseSensitive="false"></GroupingSettings>
<MasterTableView AutoGenerateColumns="false" CommandItemDisplay="TopAndBottom" DataKeyNames="Id" EditMode="InPlace" ShowHeader="true">
<Columns>
<telerik:GridBoundColumn DataField="Id" UniqueName = "Id" AllowFiltering="false" Display ="false">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn HeaderText="Days" HeaderStyle-Width="150px" ItemStyle-Width="150px" UniqueName="ScheduleDays">
<ItemTemplate>
<%# Eval("ScheduleDays") %>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox RenderMode="Lightweight" runat="server" ID="ddl_ScheduleDays" CheckedItemsTexts="DisplayAllInInput" CheckBoxes="true" SelectedValue='<%#Bind("ScheduleDays") %>' >
<Items>
<telerik:RadComboBoxItem Text="None" Value= 0 runat="server" />
<telerik:RadComboBoxItem Text="Monday" Value= 1 runat="server" />
<telerik:RadComboBoxItem Text="Tuesday" Value= 2 runat="server" />
<telerik:RadComboBoxItem Text="Wednesday" Value= 4 runat="server" />
<telerik:RadComboBoxItem Text="Thursday" Value= 8 runat="server" />
<telerik:RadComboBoxItem Text="Friday" Value= 16 runat="server" />
<telerik:RadComboBoxItem Text="Saturday" Value= 32 runat="server" />
<telerik:RadComboBoxItem Text="Sunday" Value= 64 runat="server" />
</Items>
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
Code Behind:
protected void grd_incontact_settings_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
List<SP_InContactSettings_Get_Result> lst_incontact_settings = new List<SP_InContactSettings_Get_Result>();
using (var db = new data.tarpasql())
{
lst_incontact_settings = db.SP_InContactSettings_Get().ToList();
}
grd_incontact_settings.DataSource = lst_incontact_settings;
}
public partial class SP_InContactSettings_Get_Result
{
public int Id { get; set; }
public List<int> ScheduleDays { get; set; }
}
This is what I am getting:

Related

Invalid case exception

In report page i have dropdown and datepicker fromdate and todate and button
so when i select values from dropdown and datepicker then this show error
on this line
dt=report(Convert.ToDateTime(fromdate), Convert.ToDateTime(todate), Convert.ToString(DropDownList1.SelectedValue));
error
An exception of type 'System.InvalidCastException' occurred in mscorlib.dll but was not handled in user code
Additional information: Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlInputText' to type 'System.IConvertible'
.
code
protected void Button1_Click(object sender, EventArgs e)
{
dt=report(Convert.ToDateTime(fromdate), Convert.ToDateTime(todate), Convert.ToString(DropDownList1.SelectedValue));
GridView1.DataSource = dt;
GridView1.DataBind();
}
DataTable dt = new DataTable();
public DataTable report(DateTime fromdate,DateTime todate,string IMEI)
{
DateTime fromdatee = Convert.ToDateTime(Request.Form["fromdate"]);
DateTime todatee = Convert.ToDateTime(Request.Form["todate"]);
Entities track = new Entities();
DateTime fr_date = new DateTime(fromdatee.Year, fromdatee.Month, fromdatee.Day, 0, 0, 0);
DateTime t_date = new DateTime(todatee.Year, todatee.Month, todatee.Day, 23, 59, 59);
List<spGetReport_Result> report = track.spGetReport(IMEI,fr_date,t_date).ToList();
dt.Columns.Add("Time",typeof(DateTime));
dt.Columns.Add("X",typeof(float));
dt.Columns.Add("valuenumber",typeof(int));
foreach(var c in report)
{
dt.Rows.Add(c.Time, c.X, c.valuenumber);
}
return dt;
}
HTML
<form id="form1" runat="server">
<div>
<span>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</span>
<span>
<input id="fromdate" runat="server" clientidmode="static" />
</span>
<span>
<input id="todate" runat="server" clientidmode="static" />
</span>
<span>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</span><br />
<asp:Label ID="Label1" style="margin-left: 220px;" runat="server" Text="Export to"></asp:Label>
<asp:GridView ID="GridView1" runat="server" class="display nowrap"
Width="100%" CellPadding="0"
Font-Names="Verdana" BackColor ="White" BorderColor="#CCCCCC" BorderStyle="None"
BorderWidth="1px" Font-Size="9pt">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
</div>
</form>
Because you are sending Convert.ToDateTime the HTML control instead of the string to be converted.
You should be doing this:
dt = report(Convert.ToDateTime(fromdate.Value), Convert.ToDateTime(todate.Value), DropDownList1.SelectedValue);
A very simple debugging process would have quickly showed you where the problem was.
DropDownList1.SelectedValue is already a string, so no point in converting it.
Anyway, you should check first that what's in those inputs are really valid DateTime representations by using a validator.

GridView DynamicField child property generates "table does not have column" error

I'm having a problem with DynamicFields in a GridView. I'm trying to get a field with a property from a related entity, something like "Customer.Name" in an Order entity but always get the error "The table 'Order' does not have a column named 'Customer.Name'."
I'm including the Customer entity in linq query.
If I change DynamicField by BoundField all works fine.
Edit: This is the code...
<asp:GridView ID="grvActivities" runat="server"
Caption="<%$ Resources:QuasarApp, MyOpenActivities %>" AutoGenerateColumns="false"
DataKeyNames="ActivityId" ItemType="Quasar.Model.Activity"
ShowHeaderWhenEmpty="True" AllowSorting="True"
ShowFooter="True" CssClass="table table-striped table-bordered table-hover table-condensed table-responsive"
SelectMethod="grvActivities_GetData"
UpdateMethod="grvActivities_UpdateItem"
OnRowCommand="grvActivities_RowCommand">
<Columns>
<asp:HyperLinkField ControlStyle-CssClass="nounderline fa fa-edit"
DataNavigateUrlFields="ActivityId" DataNavigateUrlFormatString="~/Activities/Edit.aspx?RecordId={0}"
ItemStyle-Width="25px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle" />
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="Complete" runat="server" CommandName="Complete" CommandArgument='<%# Eval("ActivityId") %>'
CssClass="nounderline fa fa-check-square-o" ToolTip="<%$ Resources:QuasarApp, MarkAsCompleted %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:DynamicField DataField="StartDate" DataFormatString="{0:g}" />
<asp:DynamicField DataField="DueDate" DataFormatString="{0:g}" />
<asp:DynamicField DataField="EndDate" DataFormatString="{0:g}" />
<asp:DynamicField DataField="Name" />
<asp:DynamicField DataField="Activity.Customer.Name" />
<asp:DynamicField DataField="Lead" />
<asp:DynamicField DataField="PriorityLevel" />
<asp:DynamicField DataField="ActivityType" />
<asp:DynamicField DataField="Status" />
<asp:DynamicField DataField="CreatedBy" />
<asp:ButtonField ButtonType="Link" CommandName="Delete" ControlStyle-CssClass="nounderline fa fa-eraser"
ItemStyle-Width="25px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle" />
</Columns>
</asp:GridView>
Codebehind:
public IQueryable<Activity> grvActivities_GetData()
{
var query = _uow.Activities.GetMany(a =>
a.IsActive
&& a.AccountManagerId == currentAccountManager
&& a.EndDate == null,
q => q.OrderByDescending(s => s.StartDate),
includeProperties: "Customer, Lead, ActivityType");
return query;
}
Edit2:
Hi, I've found that with this column:
<asp:TemplateField HeaderText="<%$ Resources:QuasarApp, Customer %>">
<ItemTemplate>
<asp:Label Text="<%# Item.Customer != null ? Item.Customer.Name : String.Empty %>" runat="server" />
</ItemTemplate>
</asp:TemplateField>
it works fine, but I'm loosing all sorting, etc., capabilities. Why if navigation property is comming in the datasource, DynamicField cannot found this property?
For navigational properties you should use only this:
<asp:DynamicField DataField="Customer" />
Dynamic data will show the first string property of your class. Or you can force with annotations:
[DisplayColumn("Name")]
public class Customer
But if you are using EF6 it's necessary to install the provider
[http://blogs.msdn.com/b/webdev/archive/2014/02/28/announcing-the-release-of-dynamic-data-provider-and-entitydatasource-control-for-entity-framework-6.aspx][1]
and register your model in global.asax.cs:
void Application_Start(object sender, EventArgs e)
{
MetaModel DefaultModel = new MetaModel();
DefaultModel.RegisterContext(new Microsoft.AspNet.DynamicData.ModelProviders.EFDataModelProvider(
() => new YOURCONTEXT()),
new ContextConfiguration { ScaffoldAllTables = false });
}
and finally set the page_init code:
protected void Page_Init()
{
grvActivities.SetMetaTable(MetaTable.GetTable(typeof(Activity)));
}

Telerik RadGrid (using Batch Edit) Hide / Disable Column Based on Another Column's Value

I'm trying to get RadGrid to conditionally hide or disable a field when it is in edit mode based on the value of another field.
I have been able to get this to work when the grid displays the list of items, but once the grid enters edit mode, the columns display ...
I am using OnItemDataBound to successfully conditionally display during the initial load, but setting the items when the user clicks a row to get it into batch mode is not working.
Note: PValue and CValue and in GridTemplateColumns, as is CardStatus.
public void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
foreach (GridDataItem item in RadGrid1.Items)
{
string BoundColumnValue = item["CardStatus"].Text; // accessing GridBoundColumn value using ColumnUniqueName
string BoundColumnValue2 = item["CValue"].Text;
TextBox txtbx = (TextBox)item.FindControl("CardStatus");
Label numlb = (Label)item.FindControl("CardValue");
if (txtbx.Text.Equals("True"))
{
txtbx.ForeColor = Color.Red;
numlb.Enabled = false;
numlb.BackColor = Color.Yellow;
numlb.ForeColor = Color.Red;
//Just testing to see if it would evaluate
}
else
{
txtbx.ForeColor = Color.Beige;
}
//string TemplateColumnValue = lb.Text;// accessing Label Text.
}
foreach (GridEditableItem item in RadGrid1.EditItems)
{
string BoundColumnValue = item["CardStatus"].Text; // accessing GridBoundColumn value using ColumnUniqueName
string BoundColumnValue2 = item["CValue"].Text;
TextBox txtbx = (TextBox)item.FindControl("CardStatus");
if (txtbx.Text.Equals("True"))
{
txtbx.ForeColor = Color.Red;
//numTxt.BackColor = Color.Yellow;
//numTxt.ForeColor = Color.Red;
}
else
{
txtbx.ForeColor = Color.Beige;
}
}
}
I just need to be able to selectively prevent data entry in a column
The ASPX source is below:
<telerik:RadGrid ID="RadGrid1" runat="server" AllowAutomaticUpdates="true" Height="930px" DataSourceID="SqlDataSource4" CellSpacing="0" GridLines="None" Width="640px" OnItemDataBound="RadGrid1_ItemDataBound" OnItemCreated="RadGrid1_ItemCreated" OnBatchEditCommand="RadGrid1_BatchEditCommand1" Skin="WebBlue">
<ClientSettings>
<Scrolling AllowScroll="True" UseStaticHeaders="True" />
</ClientSettings>
<MasterTableView AutoGenerateColumns="False" EditMode="Batch" Width="620px" CommandItemDisplay="TopAndBottom" DataSourceID="SqlDataSource4" DataKeyNames="CountKey">
<CommandItemSettings ExportToPdfText="Export to PDF" ShowSaveChangesButton="true" ShowRefreshButton="false" ShowAddNewRecordButton="false"></CommandItemSettings>
<BatchEditingSettings OpenEditingEvent="Click" EditType="Row" />
<RowIndicatorColumn Visible="True" FilterControlAltText="Filter RowIndicator column">
<HeaderStyle Width="20px"></HeaderStyle>
</RowIndicatorColumn>
<ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column">
<HeaderStyle Width="20px"></HeaderStyle>
</ExpandCollapseColumn>
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
</EditFormSettings>
<PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
<Columns>
<telerik:GridBoundColumn DataField="Pcolumn" ItemStyle-Width="75px" ReadOnly="true" Visible="false" DataType="System.Int32" FilterControlAltText="Filter Pcolumn column" HeaderText="Pcolumn" SortExpression="Pcolumn" UniqueName="Pcolumn">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Row" ReadOnly="true" Visible="false" DataType="System.Int32" FilterControlAltText="Filter Row column" HeaderText="Row" SortExpression="Row" UniqueName="Row">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn ColumnEditorID="PValue" HeaderText="Pattern" DataField="PValue" UniqueName="PValue" ItemStyle-Width="75px" HeaderStyle-Width="75px">
<EditItemTemplate>
<telerik:RadNumericTextBox ID="PValue" Width="50px" runat="server" MaxLength="1" MaxValue="9" NumberFormat-DecimalDigits="0" Text='<%# Bind("PValue") %>'></telerik:RadNumericTextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="PValue" ErrorMessage="<br/>Required (0-9) Only)!" SetFocusOnError="true"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="PValue" Width="50px" runat="server" Text='<%# Bind("PValue") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn ColumnEditorID="CValue" DataField="CValue" HeaderText="Card" UniqueName="CValue" ItemStyle-Width="75px" HeaderStyle-Width="75px">
<EditItemTemplate>
<telerik:RadNumericTextBox ID="CValue" Width="50px" AllowOutOfRangeAutoCorrect="false" runat="server" MaxLength="1" MaxValue="1" NumberFormat-DecimalDigits="0" Text='<%# Bind("CValue") %>'></telerik:RadNumericTextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="CValue" ErrorMessage="<br />Required (0-1 Only)!" SetFocusOnError="true"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CValue" Width="50px" runat="server" Text='<%# Bind("CValue") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="DateEdited" ReadOnly="true" Visible="false" DataType="System.DateTime" FilterControlAltText="Filter DateEdited column" HeaderText="DateEdited" SortExpression="DateEdited" UniqueName="DateEdited">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="CardStatus" DataField="CardStatus" ItemStyle-Width="50px" HeaderStyle-Width="50px">
<ItemTemplate>
<asp:TextBox ID="CardStatus" Width="10px" runat="server" Text='<%# Bind("CardStatus") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="CardStatus" Width="10px" runat="server" Text='<%# Bind("CardStatus") %>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
<PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
<FilterMenu EnableImageSprites="False"></FilterMenu>
</telerik:RadGrid>
Any help / workarounds would be appreciated ... again, "just" need to prevent editing in the CValue column when the CardStatus value is true (bit field) ... using batch mode (using another solution isn't an option now).
Thanks
Larry
Well, this doesn't answer the Telerik question, but ended up doing this with the MS GridView, using the tutorial here: http://msdn.microsoft.com/en-us/library/aa992036(v=vs.90).aspx.
Also was able to customize, and detect hidden grid fields, and hide cells (and disable validators) based on the hidden field's condition.
Added the following code in the RowDataBound event of the gridview:
DataRowView drv = (DataRowView)e.Row.DataItem;
if (drv["Status"].Equals(true))
{
// Find the order of the cell
e.Row.Cells[5].CssClass = "hiddencol"; // using the display: none style
// Find the Validator control in the template column
RequiredFieldValidator reqF = (RequiredFieldValidator)e.Row.Cells[5].FindControl("RequiredFieldValidator1");
reqF.Enabled = false;
}
else
{
}

Unable to download file using AsyncPostBackTrigger in RadGrid

Hi all I am using RadGrid in my application, as I want my RadGrid not to refresh I had my RadGrid in an Update Panel as follows
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="RadGrid1" EventName="ItemCommand" />
<%--<asp:PostBackTrigger ControlID="RadGrid1" />--%>
</Triggers>
<ContentTemplate>
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnItemCommand="RadGrid1_ItemCommand"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView Width="950" AutoGenerateColumns="false" DataKeyNames="EmpID" GridLines="None"
TableLayout="Auto">
<Columns>
<telerik:GridBoundColumn DataField="EmpID" HeaderText="Emp ID" ReadOnly="true" HeaderStyle-HorizontalAlign="Left"
ItemStyle-HorizontalAlign="Left" UniqueName="EmpID" FilterControlWidth="30px"
AutoPostBackOnFilter="true" CurrentFilterFunction="Contains" />
<telerik:GridButtonColumn DataTextField="ButtonName" ItemStyle-ForeColor="Blue" CommandName="Generate"
ConfirmTextFields="ButtonName" ConfirmTextFormatString="Would you like to {0} ACH file ?"
ConfirmDialogType="RadWindow" Reorderable="false" UniqueName="ButtonName" ConfirmTitle="ACH File">
</telerik:GridButtonColumn>
<telerik:GridBoundColumn DataField="EmployeeName" HeaderText="Employee Name" ReadOnly="true"
HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" UniqueName="EmployeeName"
FilterControlWidth="60px" AutoPostBackOnFilter="true" CurrentFilterFunction="Contains" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
</ContentTemplate>
</asp:UpdatePanel>
When I click on download button I am unable to download the file this is my code in Itemcommand
protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
if (e.CommandName == "Generate")
{
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment;filename= errorLog.txt");
Response.AddHeader("content-length", "0");
Response.Flush();
Response.End();
}
}
Can some one help me how can I work out this using AsyncPostBackTrigger
You cannot call Response with AsyncPostBack. It is Ajax Framework limitation.
Updated 1/28/2013
Since you are using telerik, I prefer using RadAjaxManager. Basically, when Generate button is clicked, it uses regular post back instead of ajax. In my example, sorting still uses ajax.
<telerik:RadGrid ID="RadGrid1" AutoGenerateColumns="false" AllowSorting="True" runat="server"
OnNeedDataSource="RadGrid1_NeedDataSource" OnItemCommand="RadGrid1_ItemCommand">
<MasterTableView DataKeyNames="EmpID">
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Button runat="server" CommandName="Generate" ID="GenerateButton"
Text="Generate" OnClientClick="Generate(this, event); return false;" />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="EmpID" HeaderText="Emp ID" UniqueName="EmpID" SortExpression="EmpID" />
<telerik:GridBoundColumn DataField="EmployeeName" HeaderText="Employee Name" UniqueName="EmployeeName" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
<%-- RadAjaxManager --%>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="RadGrid1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
<%-- RadAjaxLoadingPanel --%>
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default">
</telerik:RadAjaxLoadingPanel>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function Generate(sender, e) {
$find("<%= RadAjaxManager1.ClientID %>").__doPostBack(sender.name, "");
}
</script>
</telerik:RadCodeBlock>
public class Employee
{
public int EmpID { get; set; }
public string EmployeeName { get; set; }
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = new List<Employee>
{
new Employee {EmpID = 1, EmployeeName = "John"},
new Employee {EmpID = 2, EmployeeName = "Marry"},
new Employee {EmpID = 3, EmployeeName = "Eric"}
};
}
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == "Generate")
{
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment;filename= errorLog.txt");
Response.AddHeader("content-length", "0");
Response.Flush();
Response.End();
}
}

Getting error while updating LINQDatasource

When I try to update a LINQ data source bound to a grid view, I get the following error:
Could not find a row that matches the given keys in the original values stored in ViewState. Ensure that the 'keys' dictionary contains unique key values that correspond to a row returned from the previous Select operation.
I have specified DataKeyNames in the grid view.
Here's the HTML:
<asp:GridView ID="TaskGridView" runat="server" AutoGenerateColumns="False"
DataKeyNames="taskid,statusid,taskdescription" DataSourceID="GridDataSource"
onrowcreated="TaskGridView_RowCreated">
<Columns>
<asp:TemplateField HeaderText="taskid" InsertVisible="False"
SortExpression="taskid">
<ItemTemplate>
<asp:Label ID="TaskId" runat="server" Text='<%# Bind("taskid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="taskdescription"
SortExpression="taskdescription">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("taskdescription") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="TaskDesc" runat="server" Text='<%# Bind("taskdescription") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="url" HeaderText="url" SortExpression="url" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddStatus" DataSourceID="DropDownDataSource" DataValueField="statusid" SelectedValue="<%# Bind('Statusid') %>" DataTextField="statusdescription" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="GridDataSource" runat="server"
ContextTypeName="DailyTask.DailyTaskDBDataContext" TableName="tbl_tasks"
EnableUpdate="True">
</asp:LinqDataSource>
<asp:Button ID="btnUpdate" runat="server" onclick="btnUpdate_Click"
Text="Update" />
<asp:LinqDataSource ID="DropDownDataSource" runat="server"
ContextTypeName="DailyTask.DailyTaskDBDataContext" TableName="tbl_status">
</asp:LinqDataSource>
Here's the corresponding code:
protected void btnUpdate_Click(object sender, EventArgs e)
{
ListDictionary keyValues = new ListDictionary();
ListDictionary newValues = new ListDictionary();
ListDictionary oldValues = new ListDictionary();
try
{
keyValues.Add("taskid", ((Label)TaskGridView.Rows[0].FindControl("TaskId")).Text);
oldValues.Add("taskdescription", ((Label)TaskGridView.Rows[0].FindControl("TaskDesc")).Text);
newValues.Add("taskdescription", "New Taskk");
GridDataSource.Update(keyValues, newValues, oldValues);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
I got the problem it was in the code
I just have to use int.Parse() here because taskid is primary key
keyValues.Add("taskid", int.Parse(((Label)TaskGridView.Rows[0].FindControl("TaskId")).Text));

Resources