textboxes gets cleared while saving - c#

I have a gridview in the popup, with 3 columns, out of which 2 are textbox column. I have added the textbox dynamically in the row data bound event. when data is entered and save button is clicked,the textboxes gets cleared and the empty values are saved. can any one one help me on this. thanks in advance
code here:
for (int r = 0; r < GridView2.Rows.Count; r++)
{
string sub_details = "";
string remarks = "";
GridViewRow gRow1 = GridView2.Rows[r];
// TextBox tb = (TextBox)gRow.Cells[2].FindControl("txt");
TextBox tb1 = (TextBox)gRow1.Cells[1].FindControl("txt1");
TextBox tb2 = (TextBox)gRow1.Cells[2].FindControl("txt2");
if (tb1 != null)
{
sub_details = tb1.Text;
TextBox1.Text = sub_details;
}
if (tb2 != null)
{
remarks= tb2.Text;
}
OdbcConnection DbConnection1 = new OdbcConnection(con1);
OdbcCommand DbCommand1 = DbConnection1.CreateCommand();
try
{
DbConnection1.Open();
DbCommand1.CommandText = "insert into tbl_campboss_report(site,tdate,entered_by,entered_time,details,camp_boss,sub_details,remarks)values('" + drpSites.SelectedItem.Text + "','" + txtDate.Text + "','" + Session["uname"].ToString() + "'," + ss + ",'" + lstDetails.SelectedItem.Text + "','" + txtCampBoss.Text + "','" + sub_details + "','" + remarks + "')";
int t1 = DbCommand1.ExecuteNonQuery();
if (t1 == 1)
{
DbConnection1.Close();
}
}
catch (Exception ee)
{
DbConnection1.Close();
}
}

You can achieve this task easily by placing your textboxes inside
template fields in your footer row with a save button. There you
can save these values to the database row by row.
Using CellIndex could fail if you add a column later to your gridview.
Your database code is prone to SQL injection, I advise you to use paramterized queries
Check below example
ASPX
<asp:GridView ID="gvCustomer" runat="server" AutoGenerateColumns="False"
ShowFooter="True" EmptyDataText="<h2>No records found </h2>"
onrowdeleting="gvCustomer_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="First name">
<FooterTemplate>
First Name:<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblFirstName" Text='<%#Bind("FirstName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last name" >
<FooterTemplate>
Last Name:
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblLastName" Text='<%#Bind("LastName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Favorite fruit">
<FooterTemplate>
Favorite fruit:
<asp:DropDownList ID="ddlFavFruit" runat="server">
<asp:ListItem Text="Apple" Value="1"></asp:ListItem>
<asp:ListItem Text="Mango" Value="2"></asp:ListItem>
<asp:ListItem Text="Orange" Value="3">Tomato</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnSave" runat="server" Text="Save"
onclick="btnSave_Click" />
</FooterTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlFruits" runat="server" Enabled="False" selectedValue='<%#Bind("FruitID") %>'>
<asp:ListItem Text="Apple" Value="1"></asp:ListItem>
<asp:ListItem Text="Mango" Value="2"></asp:ListItem>
<asp:ListItem Text="Orange" Value="3">Tomato</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (ViewState["myData"] == null)
{
// initialize datatable
dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(int)));
dt.Columns.Add(new DataColumn("FirstName", typeof(string)));
dt.Columns.Add(new DataColumn("LastName", typeof(string)));
dt.Columns.Add(new DataColumn("FruitID", typeof(int)));
dt.Columns[0].AutoIncrement = true;
dt.Columns[0].AutoIncrementSeed = 1;
// Add sample data
for (int i = 0; i <= 5; i++)
{
DataRow dr = dt.NewRow();
dr["FirstName"] = "Scott";
dr["LastName"] = "Tiger";
dr["FruitID"] = "2";
dt.Rows.Add(dr);
}
ViewState["myData"] = dt;
}
else
{
dt = ViewState["myData"] as DataTable;
}
gvCustomer.DataSource = dt;
gvCustomer.DataBind();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
// fetch controls from footer
GridViewRow footerRow = ((Button)sender).NamingContainer as GridViewRow;
if (footerRow != null)
{
// Fetch footer controls
TextBox txtFirstName = footerRow.FindControl("txtFirstName") as TextBox;
TextBox txtLastName = footerRow.FindControl("txtLastName") as TextBox;
DropDownList ddlFruits = footerRow.FindControl("ddlFavFruit") as DropDownList;
// Save to datatable
dt = ViewState["myData"] as DataTable;
DataRow dr = dt.NewRow();
dr["FirstName"] = txtFirstName.Text.ToString();
dr["LastName"] = txtLastName.Text.ToString();
dr["FruitID"] = ddlFruits.SelectedValue;
dt.Rows.Add(dr);
gvCustomer.DataSource = dt;
gvCustomer.DataBind();
ViewState["myData"] = dt;
}
}

//This Metghod Will not Clear The Controls
//Keep this Method in Your .Aspx.cs Page
protected override void CreateChildControls()
{
base.CreateChildControls();
// Keep your GridView Binding Code
}

Related

Place RadioButtonList in a table column

I dynamically create my labels and Radio Button Lists in my web forms asp.net application. Afterwards, I place them in a table.
I am having a problem with displaying the actual radio button list control in the table.
How do I display the control instead of the Text being shown?
The code I have is:
string cs = ConfigurationManager.ConnectionStrings["OnlineCheckListConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter("spGetApplications", con))
{
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.SelectCommand.Parameters.AddWithValue("#uname", "rbrown");
sda.Fill(dt);
}
if (dt.Rows.Count > 0)
{
string tablestring = "<table border = \"1\" CssClass=\"TestClass\">" +
"<tr><td>First Column Heading</td><td>second Column</td></tr>";
for (int i = 0; i < dt.Rows.Count; i++)
{
Label lbl = new Label();
RadioButtonList c = new RadioButtonList();
lbl.ID = "Label" + i.ToString();
c.ID = "cbl" + i.ToString();
lbl.Text += dt.Rows[i][1].ToString() + "<br/>";
c.Items.Add(new ListItem("Yes"));
c.Items.Add(new ListItem("NO"));
c.RepeatDirection = RepeatDirection.Horizontal;
//this.Controls.Add(lbl);
//this.Form.Controls.Add(c);
tablestring = tablestring + "<tr><td>" + lbl.Text.ToString() + "</td><td>" + c + "</td></tr>";
}
divTable.InnerHtml = tablestring;
I Suggest you to use AspGridView, not plain HTML table.
You could use <ItemTemplate> and <EditItemTemplate> to add RadioButtonList in aspx.
<asp:GridView ID="gvOrders" DataKeyNames="OrderId" runat="server" AutoGenerateColumns="false"
OnRowEditing="EditCustomer" OnRowDataBound="RowDataBound" OnRowUpdating="UpdateCustomer"
CssClass="Grid" OnRowCancelingEdit="CancelEdit">
<Columns>
<asp:BoundField DataField="ContactName" HeaderText="Customer Name" ReadOnly="true" />
<asp:BoundField DataField="ShipCity" HeaderText="Ship City" ReadOnly="true" />
<asp:TemplateField HeaderText="Shipper">
<ItemTemplate>
<asp:Label ID="lblShipper" runat="server" Text='<%# Eval("CompanyName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblShipper" runat="server" Text='<%# Eval("ShipperId")%>' Visible="false"></asp:Label>
<asp:RadioButtonList ID="rblShippers" runat="server">
</asp:RadioButtonList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Then fill the data through RowDataBound
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvOrders.EditIndex == e.Row.RowIndex)
{
RadioButtonList rblShippers = (RadioButtonList)e.Row.FindControl("rblShippers");
string query = "SELECT * FROM Shippers";
SqlCommand cmd = new SqlCommand(query);
rblShippers.DataSource = GetData(cmd);
rblShippers.DataTextField = "CompanyName";
rblShippers.DataValueField = "ShipperId";
rblShippers.DataBind();
rblShippers.Items.FindByValue((e.Row.FindControl("lblShipper") as Label).Text).Selected = true;
}
}
Here is the demo:
https://www.aspsnippets.com/demos/406/default.aspx
And Complete Example:
https://www.aspsnippets.com/Articles/Populate-and-save-ASPNet-RadioButtonList-with-Selected-Value-in-Edit-ItemTemplate-of-GridView.aspx
The RadioButtonList is a WebControl, that can be used inside another WebControl. In your code you are creating a table by concatenating HTML text, therefore, outside the domain of the Web Forms view state model.
When you are concatenating c in your HTML text variable, you are just getting the value returned by c.ToString(), which by default is the full name of the type.
Having said that, please use the System.Web.UI.WebControls.Table type to build your table instead, and add the System.Web.UI.WebControls.RadioButtonList to it; I'm leaving a basic example below that you can use as a starting point:
In your aspx file (somewhere inside your form element):
<asp:Table runat="server" ID="myTable"></asp:Table>
In your code-behind file:
using System.Web.UI.WebControls;
...
void SomeMethod()
{
var row = new TableRow();
var cell = new TableCell();
var radioButtonList = new RadioButtonList();
radioButtonList.Items.Add(new ListItem("Yes"));
radioButtonList.Items.Add(new ListItem("NO"));
cell.Controls.Add(radioButtonList);
row.Cells.Add(cell);
myTable.Rows.Add(row);
}

Multiple controls in one itemtemplate - GridView

I have a gridview in web application which show textboxes in each columns in page load event. Now what I want to do is to add another label control in this itemtemplate. Show that when I type something in the textbox and click save, I can show the label instead of the textbox to my database. I got the saving part work fine but not sure how to show the text I typed in a label. What I have right now is after I clicked the save button, the textbox stay in the gridview and label not show up. Any idea how to fix this?
<asp:GridView ID='gvMain' ruant="server">
<Columns>
<asp:TemplateField HeaderText ="LastName">
<ItemTemplate>
<asp:TextBox ID="txtFName" runat="server"/>
<asp:Label ID="lblFName" ruant="server" />
</Columns>
</asp:GridView>
Please see this link for reference.
http://www.aspsnippets.com/Articles/Adding-Dynamic-Rows-in-ASP.Net-GridView-Control-with-TextBoxes.aspx
I would add both controls to a cell item template and hide/show them based on if I save a row or add a new one. So, my code would be like the following:
Markup:
<form id="form1" runat="server">
<div>
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Column1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Column2") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Column3") %>'></asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
OnClick="ButtonAdd_Click" />
<asp:Button ID="ButtonSave" runat="server" Text="Save"
OnClick="ButtonSave_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
Code-behind:
private void SetInitialRow() {
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
Table = dt;
BindGrid();
SwitchMode(false);
}
private void AddNewRowToGrid() {
if(Table != null) {
DataRow row = Table.NewRow();
Table.Rows.Add(row);
BindGrid();
SwitchMode(false);
}
else {
Response.Write("ViewState is null");
}
}
private void SaveRow() {
if(Table != null) {
int rowIndex = Table.Rows.Count - 1;
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
Table.Rows[rowIndex]["Column1"] = box1.Text;
Table.Rows[rowIndex]["Column2"] = box2.Text;
Table.Rows[rowIndex]["Column3"] = box3.Text;
BindGrid();
SwitchMode(true);
}
else {
Response.Write("ViewState is null");
}
}
private void SwitchMode(bool add) {
Button saveBtn = (Button)Gridview1.FooterRow.Cells[3].FindControl("ButtonSave");
saveBtn.Visible = !add;
Button addBtn = (Button)Gridview1.FooterRow.Cells[3].FindControl("ButtonAdd");
addBtn.Visible = add;
SwitchControl(add);
}
private void SwitchControl(bool add) {
for(int i = 0; i < Table.Rows.Count; i++) {
bool txtVisible = false;
if (i == Table.Rows.Count - 1) {
txtVisible = !add;
}
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
box1.Visible = txtVisible;
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
box2.Visible = txtVisible;
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("TextBox3");
box3.Visible = txtVisible;
Label label1 = (Label)Gridview1.Rows[i].Cells[1].FindControl("Label1");
label1.Visible = !txtVisible;
Label label2 = (Label)Gridview1.Rows[i].Cells[2].FindControl("Label2");
label2.Visible = !txtVisible;
Label label3 = (Label)Gridview1.Rows[i].Cells[3].FindControl("Label3");
label3.Visible = !txtVisible;
}
}
private DataTable Table {
get {
return ViewState["CurrentTable"] as DataTable;
}
set {
ViewState["CurrentTable"] = value;
}
}
private void BindGrid() {
Gridview1.DataSource = Table;
Gridview1.DataBind();
}
protected void Page_Load(object sender, EventArgs e) {
if(!Page.IsPostBack) {
SetInitialRow();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e) {
AddNewRowToGrid();
}
protected void ButtonSave_Click(object sender, EventArgs e) {
SaveRow();
}
So, first I see the Grid with one row and I can populate it with data via TextBoxes and click Save. Then, TextBoxes become Labels and Add New Row is visible. If I click it, a new row with TextBoxes appears.

Search in RadComboBox (inside RadGrid) on asp button click

There is a RadGrid inside which there is a RadComboBox (Say ComboIn) and there is 1 more RadComboBox outside of RadGrid (say ComboOut).
When user select any item from ComboOut, then the Items are bind in ComboIn based on selected Item of ComboOut.
I am using LoadOnDemand approach for binding the ComboIn RadComboBox.
Now I want to modify this requirement as: when user click on ComboIn textarea, whole list of items (related to selected ComboOut Item) should not load. Rather when user type/key-in/search the item in ComboIn and click on asp button then only list related to searched text shall load in ComboIn.
Below is the code I am currently using:
HTML
<telerik:RadComboBox ID="ddlCompany" runat="server" Height="200" Width="240"
DropDownWidth="310" EmptyMessage="- Select Product -" HighlightTemplatedItems="true" CausesValidation="false"
Filter="Contains" AppendDataBoundItems="true" AllowCustomText="true" AutoPostBack="true"
DataTextField="Title" DataValueField="Code" OnSelectedIndexChanged="ddlCompany_SelectedIndexChanged">
</telerik:RadComboBox>
<telerik:RadGrid ID="RGGSTAcCode" runat="server"
ShowFooter="True" GroupingEnabled="False" ShowStatusBar="true" EmptyDataText="No record available."
AllowAutomaticInserts="False" AllowAutomaticUpdates="False" AllowAutomaticDeletes="true"
OnNeedDataSource="RGGSTAcCode_NeedDataSource" OnItemDataBound="RGGSTAcCode_ItemDataBound"
OnInsertCommand="RGGSTAcCode_InsertCommand" OnDeleteCommand="RGGSTAcCode_DeleteCommand"
OnUpdateCommand="RGGSTAcCode_UpdateCommand" OnItemCommand="RGGSTAcCode_ItemCommand">
<mastertableview ShowHeadersWhenNoRecords="true" autogeneratecolumns="false" datakeynames="AccountCodeID" InsertItemDisplay="Top"
insertitempageindexaction="ShowItemOnCurrentPage" ShowFooter="True" CommandItemDisplay="Top" ClientIDMode="Static">
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn"></telerik:GridEditCommandColumn>
<telerik:GridBoundColumn DataField="AccountCodeID" HeaderText="AccountCode ID"
UniqueName="AccountCodeID" ReadOnly="True">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240" DropDownWidth="310" HighlightTemplatedItems="true" CausesValidation="true"
OnItemsRequested="ddlAccountCode_ItemsRequested" EnableItemCaching="true" ShowDropDownOnTextboxClick="false"
EnableLoadOnDemand="True" ShowMoreResultsBox="true" EnableVirtualScrolling="true" MarkFirstMatch="True"
Filter="Contains" AppendDataBoundItems="true" DataTextField="AccountDescription" DataValueField="AccountCodeID">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridButtonColumn ConfirmTextFormatString="Are you sure you want to Delete {0} Account Code?" ConfirmTextFields="AccountCodeID"
ConfirmDialogType="RadWindow" CommandName="Delete" Text="Delete" UniqueName="DeleteColumn"></telerik:GridButtonColumn>
</Columns>
<EditFormSettings>
<EditColumn ButtonType="ImageButton" />
</EditFormSettings>
<CommandItemSettings AddNewRecordText="Add new record" RefreshText="Refresh"></CommandItemSettings>
</mastertableview>
</telerik:RadGrid>
C#
public DataTable GetAccCode(string CompanyCode)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("[Invoice].[usp_tbl_AccountCode_DL_Test]", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CompanyCode", CompanyCode);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
con.Close();
}
catch (Exception ex)
{
}
return dt;
}
#region Load on Demand
private const int ItemsPerRequest = 50;
private static string GetStatusMessage(int offset, int total)
{
if (total <= 0)
{
return "No matches";
}
else
{
return String.Format("Items <b>1</b>-<b>{0}</b> out of <b>{1}</b>", offset, total);
}
}
protected void ddlAccountCode_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
string c = ddlCompany.SelectedValue.ToString();
DataTable dt = GetAccCode(c);
DataView dv = new DataView(dt);
string txt = e.Text;
dv.RowFilter = string.Format("AccountDescription LIKE '%{0}%'", txt);
int a = dv.Count;
if (dv.Count > 0)
{
dt = dv.ToTable();
}
RadComboBox combo = (RadComboBox)sender;
int itemOffset = e.NumberOfItems;
int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
e.EndOfItems = endOffset == dt.Rows.Count;
for (int i = itemOffset; i < endOffset; i++)
{
combo.Items.Add(new RadComboBoxItem(dt.Rows[i]["AccountDescription"].ToString(), dt.Rows[i]["AccountDescription"].ToString()));
}
if (!string.IsNullOrEmpty(e.Text))
{
int num = dv.Count;
endOffset = dv.Count;
}
e.Message = GetStatusMessage(endOffset, dt.Rows.Count);
}
#endregion
protected void btnSearch_Click(object sender, EventArgs e)
{
}
My code is working fine. Only thing I am not getting is how to bind only search related Items in ComboIn on asp button click. Please reply. Thanks in advance.
Below code solved my query.
Added the _ItemRequested event code inside Button_Click event with few modifications and its working fine now.
C#
protected void ddlAccountCode_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
RadComboBox combo = (RadComboBox)sender;
combo.ShowDropDownOnTextboxClick = false;
combo.Items.Clear();
Session["Text"] = e.Text;
Session["NumberOfItems"] = e.NumberOfItems;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
GridEditableItem editedItem = (sender as Button).NamingContainer as GridEditableItem;
RadComboBox combo = (RadComboBox)editedItem.FindControl("ddlAccountCode");
combo.Items.Clear();
combo.OpenDropDownOnLoad = true;
combo.HighlightTemplatedItems = true;
string c = ddlCompany.SelectedValue.ToString(); //get the selected company name
string txt = Session["Text"].ToString();
DataTable dt = new DataTable();
dt = GetAccCode(c);
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("AccountDescription LIKE '%{0}%'", txt);
int a = dv.Count;
if (dv.Count > 0)
{
dt = dv.ToTable();
}
int itemOffset = Convert.ToInt32(Session["NumberOfItems"]);
int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
Session["NumberOfItems"] = endOffset == dt.Rows.Count;
for (int i = itemOffset; i < dv.Count; i++)
{
combo.Items.Add(new RadComboBoxItem(dt.Rows[i]["AccountDescription"].ToString(), dt.Rows[i]["AccountDescription"].ToString()));
}
Label lbl = (Label)combo.Footer.FindControl("lblRadComboFooter");
lbl.Text = GetStatusMessage(endOffset, dt.Rows.Count);
combo.DataBind();
}
HTML
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240" DropDownWidth="310"
EnableLoadOnDemand="True" OnItemsRequested="ddlAccountCode_ItemsRequested" EnableItemCaching="true"
ShowMoreResultsBox="True" EnableVirtualScrolling="true" AllowCustomText="true" MarkFirstMatch="true"
Filter="Contains" HighlightTemplatedItems="true" CausesValidation="true" AppendDataBoundItems="true"
DataTextField="AccountDescription" DataValueField="AccountCodeID"
ShowDropDownOnTextboxClick="false"
OnClientDropDownOpening="OnClientDropDownOpening" OnClientItemsRequested="OnClientItemsRequested">
<FooterTemplate>
<table style="text-align:center">
<tr>
<td>
<asp:Label ID="lblRadComboFooter" runat="server"></asp:Label>
</td>
</tr>
</table>
</FooterTemplate>
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click"/>
</EditItemTemplate>

Keep values when subtracting gridview rows?

I am working with .NET Webforms in C#, and right now I am trying to add and subtract a row in a gridview on a button click. I've got an add, and remove button in the footer template, and I have the add button working alright, but removing the last row, while retaining any data that may have been entered in the others is where I am having the issue. Basically I can remove the last row, but I fill out multiple rows of data before hand, it's all erased when I remove the last row. I want to retain all the data entered, and just subtract the last row index from the gridview. here is my gridview:
<!-- ADD COURSE GRIDVIEW -->
<asp:GridView ID="Course_Gridview" runat="server" ShowFooter="True" AutoGenerateColumns="false" class="table table-striped" GridLines="None" Visible="false">
<Columns>
<asp:BoundField DataField="RowNumberCourse" HeaderText="Course #" />
<asp:TemplateField HeaderText="Course">
<ItemTemplate>
<asp:DropDownList ID="CourseList" runat="server" DataSourceID="CourseListODS" DataTextField="SubjectName"
DataValueField="CourseID" AppendDataBoundItems="true" CssClass="form-control course-ddl-fix">
<asp:ListItem Value="0">---------[Select]---------</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ErrorMessage="Please select a Program Length value from the list." Display="Dynamic" ControlToValidate="CourseList"
InitialValue="0" Text="*" CssClass="require-fix"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mark">
<ItemTemplate>
<asp:TextBox ID="EnterMark" runat="server" CssClass="form-control pgm-length-fix"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ErrorMessage="Please enter a Mark when inserting a course." Text="*" ControlToValidate="EnterMark"
Display="Dynamic" CssClass="require-fix"></asp:RequiredFieldValidator>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add Another Course..." OnClick="ButtonAdd_Click" CssClass="listview-buttons" CausesValidation="False"/>
<asp:LinkButton ID="ButtonSubtract" runat="server" CssClass="btn btn-default btn-sm delete-fix"
OnClick="ButtonSubtract_Click" CausesValidation="false">
<i aria-hidden="true" class="glyphicon glyphicon-remove"></i> Remove...</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
And here is the method for subtracting the last row:
protected void ButtonSubtract_Click(object sender, EventArgs e)
{
if (ViewState["CurrentTableCourse"] != null)
{
//create new datatable, cast datatable of viewstate
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTableCourse"];
DataRow drCurrentRow = null;
int rowIndex = 0;
if (dtCurrentTable.Rows.Count > 1)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the values
DropDownList courseList = (DropDownList)Course_Gridview.Rows[rowIndex].Cells[1].FindControl("CourseList");
TextBox marks = (TextBox)Course_Gridview.Rows[rowIndex].Cells[2].FindControl("EnterMark");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumberCourse"] = i;
dtCurrentTable.Rows[i - 1]["Column1Course"] = courseList.Text;
dtCurrentTable.Rows[i - 1]["Column2Course"] = marks.Text;
rowIndex++;
}
dtCurrentTable.Rows[rowIndex - 1].Delete();
ViewState["CurrentTableCourse"] = dtCurrentTable;
Course_Gridview.DataSource = dtCurrentTable;
Course_Gridview.DataBind();
}
}
}
How would I go about keeping all the values entered, aside from the last one which is removed?
thanks for the reply, but I just got it. I needed to add the following methods for it to work accordingly:
private void SetPreviousCourseData()
{
int rowIndex = 0;
if (ViewState["CurrentTableCourse"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTableCourse"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList courseList = (DropDownList)Course_Gridview.Rows[rowIndex].Cells[1].FindControl("CourseList");
TextBox marks = (TextBox)Course_Gridview.Rows[rowIndex].Cells[2].FindControl("EnterMark");
courseList.Text = dt.Rows[i]["Column1Course"].ToString();
marks.Text = dt.Rows[i]["Column2Course"].ToString();
rowIndex++;
}
}
}
}
Call this method if(!Page.IsPostBack):
private void SetInitialCourse()
{
//Create DataTable
DataTable dt = new DataTable();
DataRow dr = null;
//Add initail values to DataTable
dt.Columns.Add(new DataColumn("RowNumberCourse", typeof(string)));
dt.Columns.Add(new DataColumn("Column1Course", typeof(string)));
dt.Columns.Add(new DataColumn("Column2Course", typeof(string)));
//dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["RowNumberCourse"] = 1;
dr["Column1Course"] = string.Empty;
dr["Column2Course"] = string.Empty;
//dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
dr = dt.NewRow();
//Store the DataTable in ViewState
ViewState["CurrentTableCourse"] = dt;
Course_Gridview.DataSource = dt;
Course_Gridview.DataBind();
}

Textbox In gridview not saving its value in table

I have a gridview gv_Products and a gridview Gv_selected. My products gridview has a checkbox that when is checked the selected row is entered in the gv_selected gridview.
I have added a textbox in gv_selected gridiew to enter the quantity i want to reorder. The quantity that i enter loses its value after i press the submit button.
<asp:GridView ID="gvSelected" runat="server"
AutoGenerateColumns = "False" Font-Names = "Arial" CssClass="gridviewsSmall" Font-Size = "11pt"
OnRowDataBound="GridView_gvSelected_RowDataBound" EnableViewState="False"
EmptyDataText = "No Records Selected" >
<Columns>
<asp:BoundField DataField="ProductId" HeaderText="Product ID" ReadOnly="True"
SortExpression="ProductId" />
<asp:TemplateField HeaderText="Product No" SortExpression="ProductNo">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("ProductNo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Name" SortExpression="Product_name">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Product_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SupplierId" HeaderText="Supplier ID" ReadOnly="True"
SortExpression="SupplierId" />
<asp:TemplateField HeaderText="Quantity" SortExpression="Quantity">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Bind("Quantity") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSendOrder" Visible="false" runat="server" Text="Send Order"
onclick="btnSendOrder_Click" />
Here is my code behind for adding rows in gvSelected gridview
private DataTable CreateDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("ProductId");
dt.Columns.Add("ProductNo");
dt.Columns.Add("Product_name");
dt.Columns.Add("SupplierId");
dt.Columns.Add("Quantity");
dt.AcceptChanges();
return dt;
}
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("ProductId = '" + gvRow.Cells[3].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["ProductId"] = gvRow.Cells[3].Text;
dt.Rows[dt.Rows.Count - 1]["ProductNo"] = (gvRow.FindControl("Label2") as Label).Text;
dt.Rows[dt.Rows.Count - 1]["Product_name"] = (gvRow.FindControl("Label3") as Label).Text;
dt.Rows[dt.Rows.Count - 1]["SupplierId"] = (gvRow.FindControl("Label5") as Label).Text;
dt.Rows[dt.Rows.Count - 1]["Quantity"] = 0;
dt.AcceptChanges();
}
return dt;
}
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
GetData();
SetData();
BindSecondaryGrid();
}
private void BindSecondaryGrid()
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
gvSelected.DataSource = dt;
gvSelected.DataBind();
}
And here is the submit button!
protected void btnSendOrder_Click(object sender, EventArgs e)
{
t_supplier_orders newOrder = new t_supplier_orders();
newOrder.UserName = User.Identity.Name;
newOrder.Order_date = DateTime.Now;
newOrder.Order_status = "Pending";
MembershipUser myObject = Membership.GetUser();
Guid UserID = new Guid(myObject.ProviderUserKey.ToString());
newOrder.UserId = UserID;
newOrder.SupplierId = Convert.ToInt32(ddl1.SelectedValue);
newOrder.Received_date = null;
Bohemian.t_supplier_orders.AddObject(newOrder);
Bohemian.SaveChanges();
//------------------------------------------------------------------------+
// Create a new OderDetail Record for each item in the gvSelected |
//------------------------------------------------------------------------+
foreach (GridViewRow row in gvSelected.Rows)
{
{
t_supplier_orders_details od = new t_supplier_orders_details();
TextBox txt1 = (TextBox)gvSelected.FindControl("TextBox1");
od.OrderId = newOrder.OrderId;
od.ProductId = Convert.ToInt32(row.Cells[0].Text);
od.Product_name = (row.FindControl("Label3") as Label).Text;
od.ProductNo = (row.FindControl("Label2") as Label).Text;
od.Quantity = Convert.ToInt32(txt1.text);
Bohemian.t_supplier_orders_details.AddObject(od);
}
}
Bohemian.SaveChanges();
lblSuccess.Text = "The Order has been successfully sent to supplier!!";
lblSuccess.ForeColor=System.Drawing.Color.BlueViolet;
lblSuccess.Font.Bold = true;
}
I assume that you are assigning the DataSource and DataBind the GridView on every postback. That will overwite all changes.
So wrap your code in a !IsPostBack check:
protected void Page_Load()
{
if(!IsPostBack)
{
BindSecondaryGrid();
}
}
By the way, you should not store the DataTable in ViewState since that will blow it up.

Categories