Get footer row cell values of gridview - c#

I have a gridview with two textboxes in the footer. What's required is get the textbox values, store it to a datatable and then bind the same to the gridview.
I am unable to get the textbox values. They show up empty (as you can see). Where am I going wrong.
ASPX:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"
ShowFooter="true" OnRowDataBound="gv_RowDataBound"
OnRowCommand="gv_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit">
</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" Text="Update"
CommandName="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel"
CommandName="Cancel"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S.No">
<ItemTemplate>
<%#Container.DataItemIndex %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbId" runat="server" Text='<%#Eval("id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtId" runat="server" Text='<%#Eval("id") %>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewId" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtNewId"
SetFocusOnError="true"
ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NAME">
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text='<%#Eval("name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtNewName" SetFocusOnError="true"
ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete"
CommandName="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkInsert" runat="server" Text="Insert"
CommandName="Insert" ></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS:
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
DataTable dt = new DataTable();
switch (e.CommandName)
{
case "Insert":
GridViewRow fRow = gv.FooterRow;
dt.Columns.Add("id");
dt.Columns.Add("name");
dt = (DataTable)ViewState["students"];
DataRow dr = dt.NewRow();
dr["id"] = ((TextBox)fRow.FindControl("txtNewId")).Text;
dr["name"] = ((TextBox)fRow.FindControl("txtNewName")).Text;
dt.Rows.Add(dr);
ViewState["students"] = dt;
gv.DataSource = ViewState["students"];
gv.DataBind();
break;
}
}
The textboxes are txtNewId, txtNewName.

Do not use grid_Row command for insert. Use button click event
like this. It will solve your problem
protected void OnCmdInsertClick(object sender, EventArgs e)
{
//Grid's footer row
var footerRow = gv.FooterRow;
if(footerRow !=null)
{
//get your textbox instances
var txtNewId = (TextBox) footerRow.FindControl("txtNewId");
var txtNewName = (TextBox) footerRow.FindControl("txtNewName");
// Check for null
if(txtNewId !=null && txtNewName !=null)
{
var dt = (DataTable)ViewState["students"];
DataRow dr = dt.NewRow();
dr["id"] = txtNewId.Text;
dr["name"] = txtNewName.Text;
dt.Rows.Add(dr);
ViewState["students"] = dt;
gv.DataSource = ViewState["students"];
gv.DataBind();
}
}
}

In the button click event, use the following to get the actual GridViewRow of the footerL
protected void insertButton_Click(object sender, EventArgs e)
{
// This is the crux -
GridViewRow row = (GridViewRow)((sender as Button).NamingContainer);
// ...
// then you can get your textboxes
// Since we know it's an insert
dt.Columns.Add("id");
dt.Columns.Add("name");
dt = (DataTable)Session["students"];
DataRow dr = dt.NewRow();
TextBox txtnewid = (TextBox) row.FindControl("txtNewId");
TextBox txtnewName = (TextBox) row.FindControl("txtNewName");
dr["id"] = txtnewid.Text;
dr["name"] = txtnewName.Text ;
dt.Rows.Add(dr);
Session["students"] = dt;
gv.DataSource = dt;
gv.DataBind();
}
EDIT
The reason viewstate didn't work is because the viewstate lasts only between postbacks. Sessions stay alive for the duration of the user's session. The default is 20 minutes of idle time.
You would normally use ViewState for persisting data between pages during a postback.
This doesn't address best practice, it's just what it is.

Please check whether you are binding the grid view correctly in the Page Load. What i mean to say is whether you are binding with in the if condidtion
if(!IspostBack)
{
BindGridView();
}
I hope this helps. Check it out..

To bind the footer with data, use the below code
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
TextBox txtNewId = (TextBox)e.Row.FindControl("txtNewId");
txtNewId.Text = "New 01";
}
}
...and to retrieve value from the footer textbox,
TextBox txtNewId = (TextBox)gvGrid.FooterRow.FindControl("txtNewId");

protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
DataTable dt = new DataTable();
if (e.CommandName.Equals("Insert"))
{
GridViewRow fRow = gv.FooterRow;
dt.Columns.Add("id");
dt.Columns.Add("name");
dt = (DataTable)ViewState["students"];
DataRow dr = dt.NewRow();
TextBox txtnewid = (TextBox) fRow.FindControl("txtNewId");
TextBox txtnewName = (TextBox) fRow.FindControl("txtNewName");
dr["id"] = txtnewid.Text;
dr["name"] = txtnewName.Text ;
dt.Rows.Add(dr);
ViewState["students"] = dt;
gv.DataSource = ViewState["students"];
gv.DataBind();
}
}

Use This,
TextBox txtName = GridView1.FooterRow.FindControl("yourtextboxId") as TextBox;
string name = txtName.Text;
Or
GridViewRow row = ((GridView)sender).FooterRow;
TextBox txtName = (TextBox)row.FindControl("yourtextboxId");
if (txtName == null)
{
return;
}
string name = txtName.Text;

I had the same problem and the best way to get the value is using:
((TextBox)<grid_name>.FooterRow.FindControl("<textBox_id>")).Text
I hope this helps.

Related

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.

Add new rows to Asp.net grid view without refresh previous rows values

Hi I have a grid view with two columns text box and drop down list when I add values and click "ADD" button I want to add new row with Previous values,
I do it but my previous values refresh. Please help me.
This is my aspx
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:DropDownList ID="DropDownListAddress" runat="server" AutoPostBack="true">
<asp:ListItem Text="Select" Value="0"> </asp:ListItem>
<asp:ListItem Text="Address1" Value="1"> </asp:ListItem>
<asp:ListItem Text="Address2" Value="2"> </asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Button ID="ButtonADD" runat="server" Text="Add" OnClick="ButtonADD_Click" />
</div>
</form>
And this is my output
This is my CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Address", typeof(string)));
dr = dt.NewRow();
dr["Name"] = string.Empty;
dr["Address"] = string.Empty;
dt.Rows.Add(dr);
ViewState["StudentTable"] = dt;
gvStudent.DataSource = dt;
gvStudent.DataBind();
}
protected void ButtonADD_Click(object sender, EventArgs e)
{
//Add Rows
}
}
}
There are 3 stpes to do it:
Get data from GridView and save to datatable
Add new row to datatable and save datatable to viewstate
Bind datatable to gridview
private void SaveGridViewDataIntoDataTable()
{
DataTable StudentTable = ViewState["StudentTable"] as DataTable;
foreach (GridViewRow row in gvStudent.Rows)
{
//get ddl value
DropDownList DropDownListAddress = row.FindControl("DropDownListAddress") as DropDownList;
StudentTable.Rows[row.RowIndex]["Address"] = DropDownListAddress.SelectedValue;
//get name from textbox
TextBox TextBoxName = row.FindControl("TextBoxName") as TextBox;
StudentTable.Rows[row.RowIndex]["Name"] = TextBoxName.Text;
}
ViewState["StudentTable"] = StudentTable;
}
private void AddNewRowToGridView()
{
SaveGridViewDataIntoDataTable();
DataTable StudentTable = ViewState["StudentTable"] as DataTable;
StudentTable.Rows.Add("Name", "Select");
gvStudent.DataSource = StudentTable;
gvStudent.DataBind();
}
now subscribe to Gridview RowBound event
<asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvStudent_RowDataBound">
also add "RowIndex" Attribute to any of your gridview controls
<asp:TextBox ID="TextBoxName" runat="server" RowIndex='<%# Container.DisplayIndex %>'></asp:TextBox>
Code behind:
protected void gvStudent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//get name from textbox
TextBox TextBoxName = row.FindControl("TextBoxName") as TextBox;
//get ddl value
DropDownList DropDownListAddress = row.FindControl("DropDownListAddress") as DropDownList;
//get rowindex
int RowIndex = Convert.ToInt32(TextBoxName.Attributes["RowIndex"]);
//get datatable stored in viewstate
DataTable StudentTable = ViewState["StudentTable"] as DataTable;
//assign values to controls
TextBoxName.Text = StudentTable.Rows[RowIndex]["Name"].ToString();
DropDownListAddress.SelectedValue = StudentTable.Rows[RowIndex]["Address"].ToString();
}
}

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();
}

Asp.net Gridview: when add row there is no data from textboxes in gridview

this is my first question so if you don't understand it say it so i will be more specific.
This is my aspx code
<asp:GridView ID="GridView1" runat="server" Style="margin-right: 0px" CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Nummer" HeaderText="Nummer" />
<asp:TemplateField HeaderText="Omschrijving" ControlStyle-Width="300px">
<FooterTemplate>
<asp:TextBox ID="txt_omschrijvingbank" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Grootboekrekening">
<FooterTemplate>
<asp:DropDownList ID="dr_grootboek" runat="server" DataSourceID="SqlDataSource2" DataTextField="grootboekrekening" DataValueField="grootboekrekeningnummer"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Btw">
<FooterTemplate>
<asp:DropDownList ID="drp_btw" runat="server">
<asp:ListItem>Selecteer btw</asp:ListItem>
<asp:ListItem>21%</asp:ListItem>
<asp:ListItem>6%</asp:ListItem>
<asp:ListItem>0%</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Debet">
<FooterTemplate>
<asp:TextBox ID="txt_debet" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Credet">
<FooterTemplate>
<asp:TextBox ID="txt_credit" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<FooterTemplate>
<asp:Button ID="btn_voegtoe" OnClick="Button3_Click" runat="server" Text="Voeg toe" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
en this is my code behind
DataTable dt1 = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
gridVIEWData();
begin();
GridView1.DataSource = dt1;
GridView1.DataBind();
}
}
private void gridVIEWData()
{
dt1.Columns.Add(new DataColumn("Nummer", typeof(string)));
dt1.Columns.Add(new DataColumn("Omschrijving", typeof(string)));
dt1.Columns.Add(new DataColumn("Grootboekrekening", typeof(string)));
dt1.Columns.Add(new DataColumn("Btw", typeof(string)));
dt1.Columns.Add(new DataColumn("Debet", typeof(string)));
dt1.Columns.Add(new DataColumn("Credit", typeof(string)));
Session["dtInSession"] = dt1; //Saving Datatable To Session
}
protected void Button3_Click(object sender, EventArgs e)
{
if (Session["dtInSession"] != null)
dt1 = (DataTable)Session["dtInSession"]; //Getting datatable from session
TextBox Omschrijving = (TextBox)GridView1.FooterRow.FindControl("txt_omschrijvingbank");
DropDownList Grootboekrekening = (DropDownList)GridView1.FooterRow.FindControl("drp_grootboek");
DropDownList Btw = (DropDownList)GridView1.FooterRow.FindControl("drp_btw");
TextBox Debet = (TextBox)GridView1.FooterRow.FindControl("txt_debet");
TextBox Credit = (TextBox)GridView1.FooterRow.FindControl("txt_credit");
Response.Write(Credit.Text);
DataRow dr = dt1.NewRow();
dr["Nummer"] = 1;
dr["Omschrijving"] = Omschrijving.Text;
dr["Grootboekrekening"] = Grootboekrekening.SelectedItem;
dr["Btw"] = Btw.SelectedItem;
dr["Debet"] = Debet.Text;
dr["Credit"] = Credit.Text;
dt1.Rows.Add(dr);
Session["dtInSession"] = dt1; //Saving Datatable To Session
GridView1.DataSource = dt1;
GridView1.DataBind();
}
private void begin()
{
if (Session["dtInSession"] != null)
dt1 = (DataTable)Session["dtInSession"]; //Getting datatable from session
DataRow dr = dt1.NewRow();
dr["Nummer"] = 1;
dr["Omschrijving"] = string.Empty;
dr["Grootboekrekening"] = string.Empty;
dr["Btw"] = string.Empty;
dr["Debet"] = string.Empty;
dr["Credit"] = string.Empty;
dt1.Rows.Add(dr);
Session["dtInSession"] = dt1; //Saving Datatable To Session
GridView1.DataSource = dt1;
GridView1.DataBind();
}
in the footer there are a couple texboxes and a button, if you push the button it will create a new row with the data that you have write in the textbox. but here is the problem: it is creating a new row!! But there is no data in the row.
i hope some of you can help me. if you need more detail please ask
Daan.
If you are able to successfully update the data in the database, and the only problem is that it is not showing the data after update then you just need to reload the page.
Try:
Response.Redirect(Request.RawUrl);

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