Currently I'm having trouble in update function for DataGrid. It is unable capture my input in the DataGrid.
Is there a way to capture my input by using DataGrid? Because most of the information internet using GridView which is different.
Edited:
This is a DataGrid with Update, Edit and delete function.
For example,
I select a row of data and press on Edit button, fill in the data on the selected row, then press on Update button to update the selected row information.
In this situation I am unable to capture the selected row information after edited.
So, I am unable to update the row data.
Here's the Code for HTML
<asp:DataGrid ID="dgRecords" runat="server" Width="100%" DataKeyField="InsitePriceID"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="5"
OnPageIndexChanged="dgRecords_PageIndexChanged" OnSortCommand="dgRecords_SortCommand"
OnDeleteCommand="dgRecords_OnDelete" OnEditCommand="dgRecords_OnEdit" OnUpdateCommand="dgRecords_OnUpdate"
OnCancelCommand="dgRecords_OnCancel">
<AlternatingItemStyle CssClass="Data"></AlternatingItemStyle>
<ItemStyle CssClass="Data"></ItemStyle>
<HeaderStyle CssClass="ColHeader"></HeaderStyle>
<Columns>
<asp:BoundColumn Visible="False" DataField="InsitePriceID"></asp:BoundColumn>
<asp:BoundColumn DataField="ServicePartFrom" HeaderText="No. of Service Part (From)"
SortExpression="ServicePartFrom"></asp:BoundColumn>
<asp:BoundColumn DataField="ServicePartTo" HeaderText="No. of Service Part (To)"
SortExpression="ServicePartTo"></asp:BoundColumn>
<asp:BoundColumn DataField="BaseAmount" HeaderText="% from Base Amount" SortExpression="BaseAmount">
</asp:BoundColumn>
<asp:EditCommandColumn ButtonType="PushButton" CancelText="Cancel" EditText="Edit"
UpdateText="Update"></asp:EditCommandColumn>
<asp:ButtonColumn ButtonType="PushButton" CommandName="Delete" Text="Delete"></asp:ButtonColumn>
</Columns>
<PagerStyle Mode="NumericPages"></PagerStyle>
</asp:DataGrid>
<td style="width: 1014px">
<asp:Label ID="lbla" runat="server"></asp:Label>
<asp:Label ID="lblb" runat="server"></asp:Label>
<asp:Label ID="lblc" runat="server"></asp:Label>
</td>
Code behind.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ucWScr.SetValue("Insite Price");
pnlMsg.Visible = false;
BindData("");
}
}
private void BindData(string _sortExpression)
{
clsAdmin obj = new clsAdmin();
int intNoRec = 0;
DataTable tbl = obj.SearchInsitePrice();
}
protected void dgRecords_OnUpdate(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Update")
{
string strInsitePriceID = dgRecords.DataKeys[e.Item.ItemIndex].ToString();
//Error start from here
lbla.Text = e.Item.Cells[1].Text;
lblb.Text = e.Item.Cells[2].Text;
lblc.Text = e.Item.Cells[3].Text;
int intServicePartFrm = Int32.Parse(lbla.Text);
int intServicePartTo = Int32.Parse(lblb.Text);
int fltPercentBaseAmt = Int32.Parse(lblc.Text);
//Error ends here
string strUserLogin = CurrentUser.UserLogin.ToString();
DateTime dteNow = DateTime.Now;
if (strInsitePriceID != "")
{
EStatus status = webform.UpdateInsitePrice(strInsitePriceID, intServicePartFrm, intServicePartTo, fltPercentBaseAmt, strUserLogin, dteNow);
if (status != EStatus.Success) throw new Exception("Update failed.");
I solve the problem by using this method.
protected void dgRecords_OnUpdate(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Update")
{
string strInsitePriceID = dgRecords.DataKeys[e.Item.ItemIndex].ToString();
TextBox temp, temp2, temp3;
temp = (TextBox)e.Item.Cells[1].Controls[0];
temp2 = (TextBox)e.Item.Cells[2].Controls[0];
temp3 = (TextBox)e.Item.Cells[3].Controls[0];
int intServicePartFrm = Int32.Parse(temp.Text);
int intServicePartTo = Int32.Parse(temp2.Text);
int fltPercentBaseAmt = Int32.Parse(temp3.Text);
Related
Check / Select only one single Radio Button in Rad Grid or Grid View with Paging and any PageSize at Server Side Code behind in C#
My Aim is to maintain user selected asp:RadioButton inside telerik:RadGrid to be selected / checked even with the paging of the grid and with any PageSize accordingly.
The Challenges i'm facing are unable to maintain Unique GroupName for each RadioButton present for each row in Grid. Due to this i have to handle this functionality in code behind.
How ever i tried searching internet for solution which i found some javascript answers with lot of work around which i'm not satisfied with them.
<telerik:RadGrid ID="rgWithPaging" AllowPaging="True" CellSpacing="0" GridLines="None"
AllowSorting="True" runat="server" AutoGenerateColumns="False"
AllowFilteringByColumn="true" EnableLinqExpressions="false"
PagerStyle-PageSizeControlType="RadDropDownList" PagerStyle-AlwaysVisible="true" Visible="true"
OnNeedDataSource="rgWithPaging_NeedDataSource">
...........
<telerik:GridTemplateColumn HeaderText="Check One" HeaderStyle-CssClass="gradient" AllowFiltering="false" HeaderStyle-Width="10%">
<ItemTemplate>
<asp:RadioButton ID="rbWPFileName" runat="server"/>
</ItemTemplate>
</telerik:GridTemplateColumn>
...........
</telerik:RadGrid>
The Answer i came up with server side code behind is as given below:
<telerik:RadGrid ID="rgWithPaging" AllowPaging="True" CellSpacing="0" GridLines="None"
AllowSorting="True" runat="server" AutoGenerateColumns="False"
AllowFilteringByColumn="true" EnableLinqExpressions="false"
PagerStyle-PageSizeControlType="RadDropDownList" PagerStyle-AlwaysVisible="true" Visible="true"
OnNeedDataSource="rgWithPaging_NeedDataSource" OnDataBound="rgWithPaging_OnDataBound">
...........
<telerik:GridTemplateColumn HeaderText="Check One" HeaderStyle-CssClass="gradient" AllowFiltering="false" HeaderStyle-Width="10%">
<ItemTemplate>
<asp:RadioButton ID="rbWPFileName" runat="server" AutoPostBack="true" OnCheckedChanged="rbWPFileName_OnCheckedChanged"/>
</ItemTemplate>
</telerik:GridTemplateColumn>
...........
</telerik:RadGrid>
now in code behind to achieve this we need only two events
OnCheckedChanged="rbWPFileName_OnCheckedChanged" and
OnDataBound="rgWithPaging_OnDataBound"
In code behind:
protected void rbWPFileName_OnCheckedChanged(object sender, EventArgs e)
{
var rbtnSelected = sender as RadioButton;
if (rbtnSelected == null) return;
foreach (GridDataItem item in rgWithPaging.Items)
{
var radFileName = (RadioButton)item.FindControl("rbWPFileName");
if (radFileName == null) return;
radFileName.Checked = rbtnSelected.ClientID == radFileName.ClientID;
if (radFileName.Checked)
{
var position = (rgWithPaging.PageSize*rgWithPaging.CurrentPageIndex) + item.ItemIndex;
Session["Position"] = position;
}
}
}
protected void rgWithPaging_OnDataBound(object sender, EventArgs e)
{
if (Session["Position"] == null) return;
var position = (int)Session["Position"];
var pageIndex = position / rgWithPaging.PageSize;
var itemIndex = position%rgWithPaging.PageSize;
if (pageIndex == rgWithPaging.CurrentPageIndex)
{
foreach (GridDataItem item in rgWithPaging.Items)
{
var radFileName = (RadioButton)item.FindControl("rbWPFileName");
if (radFileName == null) return;
radFileName.Checked = itemIndex == item.ItemIndex;
}
}
}
that's it task done!!! enjoy..:-)
Greetings to all
Actually i'm developing a web application Which will generate DataGrid,Button and a Label at run time depends upon the value return from database.
Eg:
if return value is 2 then the 3 controls(datagrid,button and label) will generate twice.like shown below
Application working Procedure is.On click on search button the above 3 controls are generated and bind the datagrid.I have achieved this using repeater.
Now what i need is....inside that datagrid i have a button called refresh.When the Refresh button is clicked the gross weight and volume in the datagrid should display the string value,remaining columns should not get change.
Here is my aspx code:
<asp:Repeater runat="server" OnItemDataBound="repeaterSearchResult_ItemDataBound" ID="repeaterSearchResult">
<ItemTemplate>
<asp:Label ID="textBoxSearch" ForeColor="White" width="25%" runat="server"
Text="<%#Container.DataItem%>"></asp:Label>
<asp:Button ID="BTNAdd" runat="server" Text="Add" OnClick="button_click"/>
<br />
<asp:DataGrid ID="dgLCL" runat="server" AutoGenerateColumns="False"
ShowFooter="FALSE" CellPadding="3" OnItemCommand="dgLCL_Select"
OnDeleteCommand="dgLCL_Delete">
<asp:BoundColumn DataField="GrossUOMType" HeaderText="Type">
</asp:BoundColumn>
<asp:BoundColumn DataField="Volume" HeaderText="Volume">
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="DELETE">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNDelete"
ImageUrl="~/AppImages/grid-icon-delete.jpg"
ToolTip="Delete" CommandName="DeleteItem"
OnClientClick="javascript:return confirmDelete();"
AlternateText="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Add">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNAdd"
ImageUrl="~/AppImages/grid-icon-add.jpg"
ToolTip="Insert" CommandName="InsertItem"
AlternateText="Insert" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle HorizontalAlign="Left" ForeColor="#000066" BackColor="White"
Mode="NumericPages">
</PagerStyle>
</asp:DataGrid><br />
and my code behind is:
protected void repeaterSearchResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string Flag = Session["Flag"].ToString();
if (Flag=="B")
{
e.Item.FindControl("textBoxSearch").Visible = false;
e.Item.FindControl("BTNAdd").Visible = false;
}
DataGrid gv = e.Item.FindControl("dgLCL") as DataGrid;
//
Label label = e.Item.FindControl("textBoxSearch") as Label;
Session["Label"] = label.Text;
Session["FlagB"] = Flag;
Session["GV"] = gv;
gridbind(label.Text, Flag, gv);
}
void gridbind(string label,string Flag,DataGrid gv)
{
try
{
if (Session["Loading"] != null)
{
PortLName.Text = Session["Loading"].ToString();
}
if (Session["Destination"] != null)
{
PortDName.Text = Session["Destination"].ToString();
}
string SFRID = label;
if (Flag == "L")
{
sql = "Select MasterNo , MasterDate,GrossWt,GrossUOMType,Volume,tBLg_NUPKId from VW_TransLCLMaster where tBLG_mDOC_NUPKID ='107' and tBLG_NUIsActive=1 and PortOfDischargeName='" + SFRID + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (gv != null)
{
gv.DataSource = ds;
gv.DataBind();
}
}
}
catch (Exception ex)
{
}
as shown in above image i need the string values should assign to grosswt and volume on refresh button click.
Please help me thanks in advance.
In your datagrid columns add another column
<asp:TemplateColumn HeaderText="Refresh">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNRefresh"
ImageUrl="~/AppImages/grid-icon-refresh.jpg"
ToolTip="Insert" CommandName="Refresh"
AlternateText="Refresh" />
</ItemTemplate>
</asp:TemplateColumn>
In your DagaGrid's OnItemCommand event, set the text for both the cells as below
protected void dgLCL_Select(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Refresh")
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//Change the indexes to correct column index
e.Item.Cells[3].Text = "your dynamic gross weight text";
e.Item.Cells[5].Text = "your dynamic volumne text";
}
}
}
I am about to develop a web application which is used to search and fetch the data from the database as per the criteria which we enter in textboxes.
I have from place and to place once we enter the data in either textbox and hit search button it will fetch data from database and display in textbox (dynamic).
Eg:
if I enter a place kolkata and hit enter then it will count the total no of records that has the from place kolkatta. If count is 3 then 3 textboxes, 3 buttons (add) and 3 gridviews should be created dynamically. Then if we click the add button it will redirect to next page.
I have created a textbox and a button but I'm unable to create 3 gridviews and also click event for the button is not firing.
Here is my code for creating controls dynamically on search button click:
protected void BTNSearch_Click(object sender, EventArgs e)
{
if(Convert.ToInt32( Session["Count"])>0)
{
if (Flag != "")
{
LoadControls(Flag);
}
}
}
private void LoadControls(string Flag)
{
LocationName.Clear();
Session["Flag"] = Flag;
Updatesearch.Update();
dynamicTextBoxes = new TextBox[Convert.ToInt32(Session["Count"])];
dynamicButtons = new Button[Convert.ToInt32(Session["Count"])];
dynamicGV = new GridView[Convert.ToInt32(Session["Count"])];
int i;
if (Flag == "L")
{
sql = "Select PortOfDischargeName from VW_TransAIHBLMasterUpdateDetails where tBLG_NUIsActive=1 and PortOfLoadName='" + Session["Loading"].ToString() + "' group by PortOfDischargeName";
}
else if (Flag == "D")
{
sql = "Select PortOfLoadName from VW_TransAIHBLMasterUpdateDetails where tBLG_NUIsActive=1 and PortOfDischargeName='" + Session["Destination"].ToString() + "' group by PortOfLoadName";
}
else
{
sql = "";
}
SqlDataReader rdr = mobjGenlib.objDBLib.ExecuteQueryReader(sql.ToString());
while (rdr.Read())
{
LocationName.Add(rdr.GetValue(0).ToString());
}
rdr.Close();
for (i = 0; i < Convert.ToInt32(Session["Count"]); i += 1)
{
TextBox textBox = new TextBox();
textBox.ID = "myTextBox" + i.ToString();
textBox.Width = 200;
textBox.Height = 15;
//textBox.Text = String.Empty;
textBox.Text = LocationName[i].ToString();
textBox.BackColor = System.Drawing.Color.AliceBlue;
myPlaceHolder.Controls.Add(textBox);
dynamicTextBoxes[i] = textBox;
var button = new Button();
button.ID = "BtnAdd" + i.ToString();
button.Text = "Add";
//button.Click += button_Click;
button.Click += new System.EventHandler(button_click);
//btn.Click += new EventHandler(btn_Click);
myPlaceHolder.Controls.Add(button);
dynamicButtons[i] = button;
ViewState["Btn"] = dynamicButtons[i];
LiteralControl literalBreak = new LiteralControl("<br />");
myPlaceHolder.Controls.Add(literalBreak);
gv.ID = "gridview" + i;
myPlaceHolder.Controls.Add(gv);
dynamicGV[i] = gv;
BindGrid(textBox.Text, Flag, i);
LiteralControl literalBreak1 = new LiteralControl("<br />");
myPlaceHolder.Controls.Add(literalBreak1);
}
}
This is for button click:
protected void button_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
foreach (Button bt in dynamicButtons)
{
for (int i = 0; i < Convert.ToInt32(Session["Count"]); i++)
{
if (btn.ID == ("BtnAdd" + i))
{
Response.Redirect("FrmTransLCLConsolidation.aspx");
break;
}
}
}
}
**
> i dont know how to write code to the Datagrid onitemcommand and > ondeletecommand.
**
Can anyone help me to achieve this? Thanks in advance.
another issue:
aspx page:
<asp:Repeater runat="server" OnItemDataBound="repeaterSearchResult_ItemDataBound" ID="repeaterSearchResult">
<ItemTemplate>
<asp:Label ID="textBoxSearch" ForeColor="White" width="25%" runat="server" Text="<%#Container.DataItem%>"></asp:Label>
<%--<asp:TextBox ID="textBoxSearch" runat="server" Text="<%#Container.DataItem%>"></asp:TextBox>--%>
<asp:Button ID="BTNAdd" runat="server" Text="Add" OnClick="button_click"/><br />
<asp:DataGrid ID="dgLCL" runat="server" BorderWidth="1px" BorderColor="#FE9B00"
BorderStyle="Solid" BackColor="White" Font-Names="Verdana" Font-Size="XX-Small"
AutoGenerateColumns="False" ShowFooter="FALSE" CellPadding="3" align="center"
Width="700px" OnItemCommand="dgLCL_Select" OnDeleteCommand="dgLCL_Delete">
<FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
<SelectedItemStyle Font-Bold="True" ForeColor="Black" BackColor="Snow"></SelectedItemStyle>
<EditItemStyle BackColor="AntiqueWhite"></EditItemStyle>
<PagerStyle BackColor="#FDE9CB" ForeColor="#003399" HorizontalAlign="Right" Mode="NumericPages"
Position="Bottom" Font-Size="Small" Font-Bold="true" />
<AlternatingItemStyle BackColor="Snow"></AlternatingItemStyle>
<ItemStyle ForeColor="#000066" BackColor="Snow"></ItemStyle>
<HeaderStyle Font-Size="XX-Small" Font-Bold="True" Height="10px" ForeColor="#000000"
BackColor="#FFDBA6"></HeaderStyle>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNAdd" ImageUrl="~/AppImages/grid-icon-add.jpg"
ToolTip="Insert" CommandName="SelectItem" AlternateText="Insert" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="MasterNo" HeaderText="MasterNo"></asp:BoundColumn>
<asp:BoundColumn DataField="MasterDate" HeaderText="MasterDate"></asp:BoundColumn>
<asp:BoundColumn DataField="GrossWt" HeaderText="GrossWt"></asp:BoundColumn>
<asp:BoundColumn DataField="GrossUOMType" HeaderText="Type"></asp:BoundColumn>
<asp:BoundColumn DataField="Volume" HeaderText="Volume"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="DELETE">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNDelete" ImageUrl="~/AppImages/grid-icon-delete.jpg"
ToolTip="Delete" CommandName="DeleteItem" OnClientClick="javascript:return confirmDelete();"
AlternateText="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle HorizontalAlign="Left" ForeColor="#000066" BackColor="White" Mode="NumericPages">
</PagerStyle>
</asp:DataGrid><br />
</ItemTemplate>
</asp:Repeater>
Repeater is a good candidate for this problem. Instead of adding the textboxes dynamically use a repeater control here, which is then easier to maintain.
Below is the outline of what you can do.
<asp:Repeater runat="server" OnItemDataBound="repeaterSearchResult_ItemDataBound" ID="repeaterSearchResult">
<ItemTemplate>
<asp:TextBox ID="textBoxSearch" runat="server" Text="<%#Container.DataItem%>"></asp:TextBox>
<asp:Button ID="buttonAdd" runat="server" Text="Button" OnClick="button_click"/>
<asp:GridView ID="gridView" runat="server">
<%--Add the Columns you want to display--%>
</asp:GridView>
</ItemTemplate>
</asp:Repeater>
In your code, after getting the search result from the data reader, instead of creating the textbox and buttons, bind the result to the repeater
SqlDataReader rdr = mobjGenlib.objDBLib.ExecuteQueryReader(sql.ToString());
while (rdr.Read())
{
LocationName.Add(rdr.GetValue(0).ToString());
}
rdr.Close();
repeaterSearchResult.DataSource = LocationName;
repeaterSearchResult.DataBind();
In the repeaters OnItemDataBound, bind the grid view
protected void repeaterSearchResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
GridView gv = e.Item.FindControl("gridView") as GridView;
TextBox textBox = e.Item.FindControl("textBoxSearch") as TextBox;
if (gv != null)
{
//Bind gridview here
}
}
In the button click event you can redirect to the page. You can also use the command argument for the button to identify the current index if you want.
Further to your question to open a new form you can use the following method.
In your image button add onclientclick event as below.
<asp:ImageButton runat="server" OnClientClick="return openNewForm();" ID="IMGBTNAdd" ImageUrl="~/AppImages/grid-icon-add.jpg"
ToolTip="Insert" CommandName="SelectItem" AlternateText="Insert" />
Then add a javascript function to open the popup
<script type="text/javascript">
function openNewForm() {
window.open("url for the new form", "newForm", "menubar=0,resizable=1,location=0,status=0,scrollbars=1,height=500,width=600");
return false;
}
</script>
I'm having a problem,
so i have a form that contains an "insert and new" and an "insert and close" buttons .
the insert and new button lets you insert a row and reopens the form to insert another row .
but the insert and close button closes after adding a row .
Anyways my problem is the following :
I am using the command field in order to insert,update or delete from my database .
the insert and close button is working
but the insert and new button is not because I'm not being able to add a row in my table .
I just want to see if i can add an "Insert and new"button in my command field so i could use it (knowing that i already used all the buttons( delete,insert,update..) .
Thanks .
Please try with the below code snippet.
ASPX
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource"
OnItemCommand="RadGrid1_ItemCommand">
<MasterTableView CommandItemDisplay="Top" EditMode="InPlace">
<Columns>
<telerik:GridBoundColumn DataField="ID" HeaderText="ID" UniqueName="ID">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Name" HeaderText="Name" UniqueName="Name">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn>
<InsertItemTemplate>
<asp:Button ID="Button1" runat="server" Text="insert and new" CommandName="insertandnew" />
<asp:Button ID="Button2" runat="server" Text="insert and close" CommandName="insertandclose" />
</InsertItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
ASPX.CS
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
dynamic data = new[] {
new { ID = 1, Name ="Name1"},
new { ID = 2, Name = "Name2"},
new { ID = 3, Name = "Name3"},
new { ID = 4, Name = "Name4"},
new { ID = 5, Name = "Name5"}
};
RadGrid1.DataSource = data;
}
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == "insertandnew")
{
// Perform Your Insert operation
e.Canceled = true;
//Set insertmonde once again
RadGrid1.MasterTableView.IsItemInserted = true;
RadGrid1.Rebind();
}
else if (e.CommandName == "insertandclose")
{
// Perform Your Insert operation
RadGrid1.MasterTableView.IsItemInserted = false;
RadGrid1.Rebind();
}
}
I am having a problem with gridviews. Basically I am writing an aircraft information and tracking system and in the process getting to know the wonders of gridviews, but I have trouble with adding a new row to the gridview. I am able to create a new row to input the data when a button is pressed, but when I click on update, I am having some sort of postback problem that is causing that data to be forgotten and can't find a way around it. The datasource is a list of cargodoor objects that contain doubles and strings holding measurements, names etc. Here is my code.
<asp:UpdatePanel ChildrenAsTriggers="true" ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div id="divAddCargoDoor" style="width:100%" runat="server" class="AlignRight">
<asp:LinkButton ID="lbAddNewCargoDoor" runat="server"
Text="<%$ Resources:ls, AddCargoDoor %>"
OnClick="lbAddNewCargoDoor_Click"></asp:LinkButton><br /><br />
</div>
<div id="divCargoDoorNoDoors" runat="server">
<asp:Label ID="lCargoDoorNoDoors" runat="server"
Text="<%$ Resources:ls, NoCargoDoors %>"></asp:Label>
</div>
<asp:GridView ID="gvCargoDoors" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id" Width="100%"
OnRowEditing="gvCargoDoors_RowEditing"
OnRowUpdating="gvCargoDoors_RowUpdating"
OnRowDeleting="gvCargoDoors_RowDeleting"
OnRowCancelingEdit="gvCargoDoors_RowCancellingEdit">
<Columns>
<asp:CommandField AccessibleHeaderText="Edit" ShowEditButton="True" />
<asp:TemplateField AccessibleHeaderText="Name"
HeaderText="<%$ Resources:ls, Description %>">
<ItemTemplate>
<asp:Label ID="lName" runat="server" Text='<%# Bind("Name") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Name" runat="server" Text='<%# Bind("Name") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Width"
HeaderText="<%$ Resources:ls, Width %>">
<ItemTemplate>
<asp:Label ID="lWidth" runat="server" Text='<%# Bind("Width") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="CDWidth" runat="server" Text='<%# Bind("Width") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Height"
HeaderText="<%$ Resources:ls, Height %>">
<ItemTemplate>
<asp:Label ID="lHeight" runat="server" Text='<%# Bind("Height") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="CDHeight" runat="server" Text='<%# Bind("Height") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField AccessibleHeaderText="Delete" ShowDeleteButton="True"
DeleteText="X" />
</Columns>
</asp:GridView>
<br />
</ContentTemplate>
</asp:UpdatePanel>
Now for the C# code
First we have this piece that gets the information from the database that is used to build the datasource. It calls a simple sql database call to the SQL Server 2008 database and returns the data in an aircraft object, that contains a list of cargodoor objects.
private void BuildDataSource()
{
this.ac = Charter.Aircraft.Retrieve(Convert.ToInt32(this.hfAircraftID.Value));
}
Now here is the code for the actual cargo door controls
private void BindCargoDoors()
{
if (ac.CargoDoors.Count == 0)
{
//display a label telling user there are no cargo doors
divCargoDoorNoDoors.Visible = true;
}
else
{
//bind the cargodoor object list to the gridview
divCargoDoorNoDoors.Visible = false;
this.gvCargoDoors.DataSource = this.ac.CargoDoors;
this.gvCargoDoors.DataBind();
}
}
protected void gvCargoDoors_RowEditing(object sender, GridViewEditEventArgs e)
{
//get the index of the row and enter row editing mode
this.gvCargoDoors.EditIndex = e.NewEditIndex;
BuildDataSource();
BindCargoDoors();
}
protected void gvCargoDoors_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//get the row being edited
GridViewRow row = this.gvCargoDoors.Rows[e.RowIndex];
//create a new cargo door to store the info in
CargoDoor cd = new CargoDoor();
//Retrieve the id of the cargodoor
cd.Id = Convert.ToInt32(gvCargoDoors.DataKeys[e.RowIndex].Values["Id"]);
if (cd.Id == 0) //will apply when new cargodoor is added
{
//fill in the cargodoor object from data in the row
cd.DateAdded = DateTime.Now;
cd.DateModified = DateTime.Now;
cd.Name = ((TextBox)row.FindControl("Name")).Text;
cd.Width = Convert.ToDouble(((TextBox)row.FindControl("Width")).Text);
cd.Height = Convert.ToDouble(((TextBox)row.FindControl("Height")).Text);
cd.Owner = this.ac.Owner;
cd.AircraftId = this.ac.Id;
//insert the new cargodoor into the database
Charter.Aircraft.InsertCargoDoor(cd);
}
else
{
//Retrieve old cargodoor info and fill in object info into cd
CargoDoor cdOrig = Charter.Aircraft.RetrieveCargoDoorByID(cd.Id);
//fill in the cargodoor object with retrieved info
cd.AircraftId = cdOrig.AircraftId;
cd.DateAdded = cdOrig.DateAdded;
cd.Notes = cdOrig.Notes;
cd.Owner = cdOrig.Owner;
//fill in updated information
cd.Name = ((TextBox)row.FindControl("Name")).Text;
cd.Width = Convert.ToInt32(((TextBox)row.FindControl("Width")).Text);
cd.Height = Convert.ToInt32(((TextBox)row.FindControl("Height")).Text);
cd.DateModified = DateTime.Now;
//save the new cargodoor info
Charter.Aircraft.UpdateCargoDoor(cd);
}
//rebuild data source to get new cargo door
BuildDataSource();
//Reset the edit index.
this.gvCargoDoors.EditIndex = -1;
//Bind data to the GridView control.
BindCargoDoors();
}
protected void gvCargoDoors_RowCancellingEdit(object sender,
GridViewCancelEditEventArgs e)
{
this.gvCargoDoors.EditIndex = -1;
BuildDataSource();
BindCargoDoors();
}
protected void gvCargoDoors_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
BuildDataSource();
int id = Convert.ToInt32(gvCargoDoors.DataKeys[e.RowIndex].Values["Id"]);
Charter.Aircraft.DeleteCargoDoor(id);
BuildDataSource();
BindCargoDoors();
}
protected void lbAddNewCargoDoor_Click(object sender, EventArgs e)
{
//trigger the edit mode with an edit row index of 0
this.gvCargoDoors.SetEditRow(0);
//insert a new cargodoor into the source object
this.ac.CargoDoors.Insert(0, new CargoDoor());
//bind the data
this.gvCargoDoors.DataSource = this.ac.CargoDoors;
BindCargoDoors();
}
My big problem is to do with the lbAddNewCargoDoor and the editing of a row. When the update link is pressed it has forgotten that a new row was added and so just edits the row that already exists, rather than inserting a new cargodoor object into the database. I am just not sure on the order of operations to prevent this from screwing up.
Any help would be appreciated. Thanks.
try changing (see the change in order of statements)
protected void lbAddNewCargoDoor_Click(object sender, EventArgs e)
{
//trigger the edit mode with an edit row index of 0
this.gvCargoDoors.SetEditRow(0);
//insert a new cargodoor into the source object
this.ac.CargoDoors.Insert(0, new CargoDoor());
//bind the data
this.gvCargoDoors.DataSource = this.ac.CargoDoors;
BindCargoDoors();
}
to
protected void lbAddNewCargoDoor_Click(object sender, EventArgs e)
{
//insert a new cargodoor into the source object
this.ac.CargoDoors.Insert(0, new CargoDoor());
//bind the data
this.gvCargoDoors.DataSource = this.ac.CargoDoors;
//trigger the edit mode with an edit row index of 0
this.gvCargoDoors.SetEditRow(0);
BindCargoDoors();
}
Please note that I cannot add comments (due to less reputation) and I am aware that this should be a comment.