Updating records using radgrid - c#

here is my code
aspx
<telerik:GridEditCommandColumn HeaderStyle-Width="25px" EditImageUrl="../images/Edit.gif"
ButtonType="ImageButton" ItemStyle-HorizontalAlign="Right">
</telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn HeaderText="Comments" HeaderStyle-Width="400px" DataField="Comments"
HeaderStyle-CssClass="tblHeaderNoBorder">
<ItemTemplate>
<asp:Label runat="server" ID="lblComments" Text='<%# Eval("Comments") %>' />
</ItemTemplate>
<EditItemTemplate>
<telerik:RadTextBox ID="txtComments" runat="server" Height="40px" Width="100%" TextMode="MultiLine"
Enabled="true" Text='<%# Eval("Comments") %>' BackColor="LightPink">
</telerik:RadTextBox></EditItemTemplate>
</telerik:GridTemplateColumn>
aspx.cs
protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
{
if ((e.Item is GridEditableItem) && (e.Item.IsInEditMode))
{
GridEditableItem item = (GridEditableItem)e.Item;
RadTextBox txtComments = (RadTextBox)item.FindControl("txtComments");
RadGrid1.DataBind();
}
here's the scenario, when i click on the update this must update the record.
how can i update the record? please help me.
I also set AllowAutomaticUpdate = "true"

Check if you have put update command or not.
You must have to create update command of the datasource related to radgrid otherwise it can't update.
otherwise you have to put update logic in
protected void RadGrid1_UpdateCommand

Related

Bind Details View in Insert Mode

I've been searching everywhere to solve this and now it's time to ask.
Here's the details view:
<asp:DetailsView ID="dvConnPipe" runat="server" AutoGenerateRows="False" ForeColor="#333333"
GridLines="None" Width="100%">
<Fields>
<asp:TemplateField HeaderText="Connection Pipe 1" SortExpression="ConnectionPipe1">
<EditItemTemplate>
<asp:TextBox ID="txtConnectionPipe1" runat="server" Text='<%# Bind("ConnectionPipe1") %>'
onkeydown="return FloatOnly(event)"></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txtConnectionPipe1" runat="server" Text='<%# Bind("ConnectionPipe1") %>' onkeydown="return FloatOnly(event)"></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ConnectionPipe1") %>'></asp:Label>
</ItemTemplate>
<ControlStyle Width="50px" />
</asp:TemplateField>
</Fields>
</asp:DetailsView>
And a dropdown list selected index changed:
protected void ddlFormItem_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlFormItem = (DropDownList)sender;
if (ddlFormItem.SelectedValue != "-1")
{
int CopyID = int.Parse(ddlFormItem.SelectedValue);
//SetInsertMode(); //If insert mode, does not bind
//SetReadOnlyMode(); //If read only, it binds OK
BindViews(CopyID);
}
}
private void BindViews(int CopyID)
{
DataTable dt = BLL.SOCBll.GetConditions(CopyID);
dvConnPipe.DataSource = dt;
dvConnPipe.DataBind();
//More views below
}
It must be possible to bind a details view while in insert mode.
If I change to read only, it binds OK.
I do not want to find each control and set it that way.
Well, after a lot of searching I did discover that you can NOT bind a detail view while in insert mode. For all the views, I had to find each control and set the default values.

How to display in value in dropdown list in grideview on selected index change

I have a dropdown down after postback i want to bind the second dropdown . i get the value but that is not displayed in the second data:EntityDropDownList .
<ItemTemplate>
<data:EntityDropDownList runat="server" ID="dataServiceTypeId" Enabled="false" DataSourceID="ServiceTypeIdServiceTypesDataSource"
DataTextField="ServiceCode" DataValueField="ServiceTypeId" SelectedValue='<%# Bind("ServiceTypeID") %>'
AppendNullItem="true" Required="true" NullItemText="< Please Choose ...>" ErrorText="Required" />
<data:ServiceTypesDataSource ID="ServiceTypeIdServiceTypesDataSource" runat="server"
SelectMethod="GetAll" />
</ItemTemplate>
<EditItemTemplate>
<data:EntityDropDownList runat="server" ID="dataServiceTypeId" DataSourceID="ServiceTypeIdServiceTypesDataSource" OnSelectedIndexChanged="Service_SelectChange" AutoPostBack="true"
DataTextField="ServiceCode" DataValueField="ServiceTypeId" SelectedValue='<%# Bind("ServiceTypeID") %>'
AppendNullItem="true" Required="true" NullItemText="< Please Choose ...>" ErrorText="Required" />
<data:ServiceTypesDataSource ID="ServiceTypeIdServiceTypesDataSource" runat="server"
SelectMethod="GetAll" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Default">
<ItemTemplate>
<asp:CheckBox ID="chkDefault" Checked='<%# Bind("IsDefault") %>' Enabled="false" runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkDefault" Checked='<%# Bind("IsDefault") %>' runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Plan">
<ItemTemplate>
<data:EntityDropDownList runat="server" ID="dataPricePlanId" Width="200px" />
</ItemTemplate>
<EditItemTemplate>
<data:EntityDropDownList runat="server" ID="dataPricePlanId" Width="200px" AppendNullItem="true" NullItemText="< Please Choose ...>" />
</EditItemTemplate>
</asp:TemplateField>
And my code is this
protected void Service_SelectChange(object sender, EventArgs e)
{
dataPricePlanId.Items.Clear();
string sValue = ((EntityDropDownList)sender).SelectedValue;
int ServiceTypeId = Convert.ToInt32(sValue);
TList<PricePlans> _pricePlans = _pricePlanService.GetByServiceTypeId(ServiceTypeId);
_pricePlanService.DeepLoad(_pricePlans);
if (_pricePlans.Count > 0)
{
dataPricePlanId.DataSource = _pricePlans;
dataPricePlanId.DataTextField = "Description";
dataPricePlanId.DataValueField = "PricePlanId";
dataPricePlanId.DataBind();
}
else
{
dataPricePlanId.Items.Insert(0, new ListItem("No Plan For this Service", "0"));
}
}
i get value but my grid is not binding in second dropdownlist. Can you please help me .
Try to do it in itemdatabound event
first find drowdown using e.item.findcontrol("dropdownname").
then bind it with datasource and then set selected value.
thanks

Insert new line, not getting text from textboxes

I'm having problems with a web app. I have a gridview connected with SQL datatable and in the footer I have textboxes (or dropdownlists) and an "insert" button. The problem occurs when I click on the button, and want to insert new line in my SQL table. It does not read text (we need to put in some strings) from textboxes. Of course insert does not happen, since some of the data must not be null.
I have the same problem with Editing rows.
this is my code:
Gridview:
<asp:GridView ID="gvUser" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" OnRowDataBound="gvUser_RowDataBound"
OnRowCommand="gvUser_RowCommand" ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewName" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last name">
<ItemTemplate>
<asp:Label ID="lblLname" runat="server" Text='<%# Bind("lname") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLname" runat="server" Text='<%# Bind("lname") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewLname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<FooterTemplate>
<asp:LinkButton ID="lnkAdd" runat="server" CausesValidation="False" CommandName="Insert"
Text="Shrani"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void BindGV()
{
//bind the SQL table to the GridView (no problem here)
}
protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e)
{
//here I bind the dropdownlist (did not include it in code snippet,
//since firstly I need to get text from textboxes
}
protected void gvUser_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtNewName = (TextBox)gvUser.FooterRow.FindControl("txtNewName");
TextBox txtNewLname = (TextBox)gvUser.FooterRow.FindControl("txtNewLname");
string NewName = txtNewName.Text; //this strings come up empty (just "")
string NewLname = txtNewLname.Text; //it should read from textboxes
AddRow(NewName, NewLname);
BindGV();
}
}
private void AddRow(string name, string lname)
{
//insert row into SQL datatable
}
EDIT:
Well it works now. Found a simmilar problem, and the author said he was able to get it work with adding EnableViewState="false" to the Gridview.
I tried and it worked. :)
Anyone here able to answer why would this work? And how will this correspond with other gv functions?
Try with this code - based on e.Item.FindControl
if (e.CommandName.Equals("Insert"))
{
TextBox txtNewName = (TextBox)e.Item.FindControl("txtNewName");
TextBox txtNewLame = (TextBox)e.Item.FindControl("txtNewLname");
....
}

GridView RowDataBound Handler - Can't get data from row

I have a GridView with an anonymous type. I need to check the value in a cell and highlight that cell if a condition is met. The problem is, I always get an empty string when I try to pull data out of the row's cells. I have successfully highlighted all the cells and I have checked in the Visual Studio 2010 debugger and confirmed that the Row has data (the row's DataItem has the values I need). This is happening on a PostBack, I'm not sure if that's a problem or not.
Here is the code and solutions I've tried:
protected void grvValidCourses_RowDataBound(Object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
String str = e.Row.Cells[6].Text.ToString(); // empty string
Label lbl = (Label) grvValidCourses.FindControl("lblEndDate"); // null
DataRowView rowView = (DataRowView)e.Row.DataItem; // exception about casting anonymous type
What's going on here? Why can't I get data from the cells?
Markup for GridView:
<asp:GridView ID="grvValidCourses" runat="server" Width="790px" OnRowCancelingEdit="grvValidCourses_RowCancelingEdit"
OnRowEditing="grvValidCourses_RowEditing" OnRowUpdating="grvValidCourses_RowUpdating" OnRowDeleting="grvValidCourses_RowDeleting"
AutoGenerateColumns="False" OnSelectedIndexChanged="grvValidCourses_SelectedIndexChanged"
OnRowDataBound="grvValidCourses_RowDataBound" >
<Columns>
<asp:CommandField ShowEditButton="True" EditText="Edit" UpdateText="Update |" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lbnDelete" runat="server" CausesValidation="False" CommandName="Delete"
Text='<%# (Eval("active") == null ? "Delete" : ((Eval("active").ToString() == "0" ? "Restore" : "Delete"))) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" SelectText="Details" />
<asp:TemplateField HeaderText="Training Name" SortExpression="coursename">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("coursename") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("coursename") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ttNo" HeaderText="#" SortExpression="ttNo" ReadOnly="True" />
<asp:TemplateField HeaderText="Course Date" SortExpression="startDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("startdate", "{0:M/d/yyyy}") %>'></asp:TextBox>
<asp:CalendarExtender ID="TextBox3_CalendarExtender" runat="server" Enabled="True"
TargetControlID="TextBox3" Format="M/d/yyyy">
</asp:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("startdate", "{0:M/d/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expiry Date" SortExpression="endDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("enddate", "{0:M/d/yyy}") %>'></asp:TextBox>
<asp:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" Enabled="True"
TargetControlID="TextBox1" Format="M/d/yyyy">
</asp:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEndDate" runat="server" Text='<%# Bind("enddate", "{0:M/d/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>No valid courses found.</EmptyDataTemplate>
</asp:GridView>
UPDATE: I've been trying all your suggestions, but I get exceptions or nulls or empty strings. I've even re-created the problem in a simpler example and still can't figure it out! I'll keep trying though, and I appreciate any new suggestions.
Part 1 - Missing Text
You are probably getting blank values in the first part due to a need to access a child control:
String str = ((DataBoundLiteralControl)e.Row.Cells[6].Controls[0]).Text;
To see if your cells have any values in debug mode (check text in debug output window):
void grvValidCourses_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Diagnostics.Trace.WriteLine(e.Row.Cells.Count);
foreach (TableCell c in e.Row.Cells)
{
System.Diagnostics.Trace.WriteLine(c.Text);
}
}
}
Part 2 - Missing Control
This is wrong:
Label lbl = (Label) grvValidCourses.FindControl("lblEndDate"); // null
You can't search the gridview for a row's control. You need to search the row.
Label lblProductOptionGrpName = (Label)e.Row.FindControl("lblProductOptionGrpName");
Part 3 - Accessing DataItem
DataBinder.Eval(e.Row.DataItem, "ColumnName")
Finally, I'm not sure what you're doing with your anonymous types, but you may need to check the contents before accessing properties:
if(MyControl.GetType() == typeof(HyperLink))
{
HyperLink TestLink = (HyperLink)MyControl;
TestLink .Visible = false;
}
Okay I finally figured out what is going on! I can only access the bound field through the row (e.g. e.Row.Cells[index].Text). So I used the bound field to get the ID of my item, then found the item in the database, got the date, compared it, and highlighted the row's cells. Not the most efficient way, but it works.
Code from simple sample:
Grid View Front End
<asp:GridView ID="gdv" runat="server" AutoGenerateColumns="True" OnSelectedIndexChanged="gdv_SelectedIndexChanged">
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="Select" />
<asp:BoundField DataField="id" HeaderText="#" ReadOnly="True" />
<asp:TemplateField HeaderText="CategoryName" >
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" >
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("desc") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblSelected" runat="server" Text="No row selected"></asp:Label>
Code Behind Page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
var qry = ctx.Categories
.Select(c => new {
id = c.CategoryID,
name = c.CategoryName,
desc = c.Description,
});
gdv.DataSource = qry;
gdv.DataBind();
}
}
protected void gdv_SelectedIndexChanged(object sender, EventArgs e) {
selectRow();
}
private void selectRow() {
GridViewRow row = gdv.SelectedRow;
String strId = row.Cells[1].Text; // Bound Field column
lblSelected.Text = strId;
// use ID to get object from database...
}
If you can post markup, then it will be possible to figure out your issue.
You are doing this in wrong way,
this DataRowView rowView = (DataRowView)e.Row.DataItem;
should be DataRow rowView = ((DataRowView)e.Row.DataItem).Row;
protected void gridPanne_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
Label label = (Label)e.Row.FindControl("Label4");
lbl.Text += " ** / ** "+label.Text;
}
}

Gridview FooterRow textbox text is null when accessing from code behind

I have a GridView with the following columns
<asp:TemplateField HeaderText="Name">
<FooterTemplate>
<asp:TextBox ID="txt_Name" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_name" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "t_Name") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_name" runat="server" Width="100px" Text='<%#DataBinder.Eval(Container.DataItem,"t_Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created By">
<ItemTemplate>
<asp:Label ID="lbl_tabcreatedby" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "t_CreatedBy") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Modify" ShowEditButton="True" />
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
<asp:TemplateField HeaderText="Add a New Name">
<FooterTemplate>
<asp:LinkButton ID="lnkbtn_AddName" runat="server" CommandName="Insert">Add Name</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
And then in the Code Behind I am trying to access the txt_Name Textbox as
protected void gv_Name_RowCommand(object sender, GridViewCommandEventArgs e)
{
string t_Name = ((TextBox)(gv_Name.FooterRow.FindControl("txt_Name"))).Text;
// Insert Code
}
But I am getting null in the string t_Name everytime irrespective of what is the current Text of txt_Name.
However I can get the text if I disable the ViewState for the page. Any explanation.
I have got around this problem by using an additional variable, see the following:
Dim txtBox As TextBox = GridView1.FooterRow.FindControl("txtName")
Dim name As String = txtBox.Text
or you can try getting the textbox by column index, like following:
protected void gv_Name_RowCommand(object sender, GridViewCommandEventArgs e)
{
string t_Name = ((TextBox)(gv_Name.FooterRow.Cells[5].FindControl("txt_Name"))).Text;
// Insert Code
}
Try following code in gv_Name_RowCommand event
if (e.CommandName.Equals("Insert"))
{
string t_Name = ((TextBox)(gv_Name.FooterRow.FindControl("txt_Name"))).Text;
}
this should work
i think you data grid is being disconnected from the data source upon post back. If you are sure that data/ data value coming from db is not null.

Categories

Resources