edit row in gridview - c#

I would like to help me with my code. I have 2 gridviews. In the first gridview the user can choose with a checkbox every row he wants. These rows are transfered in the second gridview. All these my code does them well.Now, I want to edit the quantity column in second gridview to change the value but i don't know what i must write in edit box.
Here is my code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
public partial class ShowLand : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPrimaryGrid();
BindSecondaryGrid();
}
}
private void BindPrimaryGrid()
{
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string query = "select * from Land";
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
sda.Fill(dt);
gridview2.DataSource = dt;
gridview2.DataBind();
}
private void GetData()
{
DataTable dt;
if (ViewState["SelectedRecords1"] != null)
dt = (DataTable)ViewState["SelectedRecords1"];
else
dt = CreateDataTable();
CheckBox chkAll = (CheckBox)gridview2.HeaderRow
.Cells[0].FindControl("chkAll");
for (int i = 0; i < gridview2.Rows.Count; i++)
{
if (chkAll.Checked)
{
dt = AddRow(gridview2.Rows[i], dt);
}
else
{
CheckBox chk = (CheckBox)gridview2.Rows[i]
.Cells[0].FindControl("chk");
if (chk.Checked)
{
dt = AddRow(gridview2.Rows[i], dt);
}
else
{
dt = RemoveRow(gridview2.Rows[i], dt);
}
}
}
ViewState["SelectedRecords1"] = dt;
}
private void SetData()
{
CheckBox chkAll = (CheckBox)gridview2.HeaderRow.Cells[0].FindControl("chkAll");
chkAll.Checked = true;
if (ViewState["SelectedRecords1"] != null)
{
DataTable dt = (DataTable)ViewState["SelectedRecords1"];
for (int i = 0; i < gridview2.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gridview2.Rows[i].Cells[0].FindControl("chk");
if (chk != null)
{
DataRow[] dr = dt.Select("id = '" + gridview2.Rows[i].Cells[1].Text + "'");
chk.Checked = dr.Length > 0;
if (!chk.Checked)
{
chkAll.Checked = false;
}
}
}
}
}
private DataTable CreateDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");
dt.Columns.Add("price");
dt.Columns.Add("quantity");
dt.Columns.Add("total");
dt.AcceptChanges();
return dt;
}
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["id"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["name"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["price"] = gvRow.Cells[3].Text;
dt.Rows[dt.Rows.Count - 1]["quantity"] = gvRow.Cells[4].Text;
dt.Rows[dt.Rows.Count - 1]["total"] = gvRow.Cells[5].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
GetData();
SetData();
BindSecondaryGrid();
}
private void BindSecondaryGrid()
{
DataTable dt = (DataTable)ViewState["SelectedRecords1"];
gridview3.DataSource = dt;
gridview3.DataBind();
}
}
and the source code is
<asp:GridView ID="gridview2" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource5">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False"
ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="name" HeaderText="name"
SortExpression="name" />
<asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
<asp:BoundField DataField="quantity" HeaderText="quantity"
SortExpression="quantity" />
<asp:BoundField DataField="total" HeaderText="total" SortExpression="total" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Land]"></asp:SqlDataSource>
<br />
</div>
<div>
<asp:GridView ID="gridview3" runat="server"
AutoGenerateColumns = "False" DataKeyNames="id"
EmptyDataText = "No Records Selected" >
<Columns>
<asp:BoundField DataField = "id" HeaderText = "id" />
<asp:BoundField DataField = "name" HeaderText = "name" ReadOnly="True" />
<asp:BoundField DataField = "price" HeaderText = "price"
DataFormatString="{0:c}" ReadOnly="True" />
<asp:TemplateField HeaderText="quantity">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("quantity")%>'</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField = "total" HeaderText = "total"
DataFormatString="{0:c}" ReadOnly="True" />
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:Label ID="totalLabel" runat="server"></asp:Label>
<br />
</div>
</form>
</body>
</html>

This is not particular asp.net solution but that's how I do something like this in my Windows app.
First of all you shoul make shure that there's a selected row in your GridView (gridView.SelectedRow != null). DataTable object allows you to get access to desired row by accessing it not by numeric index but by DataRow-type object index. After getting a reference to the row which fields' value you want to modify just go ahead with changes.
Here's the example:
if (gridView.SelectedRow != null)
{
dataTable.Rows[gridView.SelectedRow].BeginEdit();
dataTable.Rows[gridView.SelectedRow]["yourFieldName"] = newValue;
dataTable.Rows[gridView.SelectedRow].EndEdit();
gridView.DataSource = dataTable;
}
Hope my answer is of any help because I've never dealt with asp.net before.

Related

Binding GridView Columns to CheckBoxList Dynamically in C#

I want to bind only Table Columns to CheckBoxList and then the selected columns should be displayed in a GridView.
My code so far is:
public void BindCheckBoxList(DataSet ds)
{
int i = 0;
foreach (DataColumn dc in ds.Tables[0].Columns)
{
ListItem li = new ListItem(dc.ToString(), i.ToString());
CheckBoxList1.Items.Add(li); i++;
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="HobbyId">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Eval("IsSelected") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Hobby" HeaderText="Hobby" ItemStyle-Width="150px" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />
in aspx.cs code
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [HobbyId], [Hobby], [IsSelected] FROM Hobbies"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void mainGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate))
{
if (e.Row.Cells[1].FindControl("selectCheckbox") == null)
{
CheckBox selectCheckbox = new CheckBox();
//Give id to check box whatever you like to
selectCheckbox.ID = "newSelectCheckbox";
e.Row.Cells[1].Controls.Add(selectCheckbox);
}
}
}
i think you use this code.
Here a complete example to hide GridView Columns based on a CheckBoxList.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//fill the datatable from the database
DataTable dt = //fill the table here...
//bind the table to the grid
GridView1.DataSource = dt;
GridView1.DataBind();
//loop all the datatable columns to fill the checkboxlist
for (int i = 0; i < dt.Columns.Count; i++)
{
CheckBoxList1.Items.Insert(i, new ListItem(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName, true));
}
}
}
protected void CheckBoxList1_TextChanged(object sender, EventArgs e)
{
//loop all checkboxlist items
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected == true)
{
//loop all the gridview columns
for (int i = 0; i < GridView1.Columns.Count; i++)
{
//check if the names match and hide the column
if (GridView1.HeaderRow.Cells[i].Text == item.Value)
{
GridView1.Columns[i].Visible = false;
}
}
}
}
}
And on the .aspx page
<asp:CheckBoxList ID="CheckBoxList1" runat="server" OnTextChanged="CheckBoxList1_TextChanged" AutoPostBack="true"></asp:CheckBoxList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="field01" HeaderText="Column A" />
<asp:BoundField DataField="field02" HeaderText="Column B" />
<asp:BoundField DataField="field03" HeaderText="Column C" />
<asp:BoundField DataField="field04" HeaderText="Column D" />
<asp:BoundField DataField="field05" HeaderText="Column E" />
</Columns>
</asp:GridView>
Note that AutoGenerateColumns is set to false. If they are auto-generated the columns are not part of the GridView Columns Collection.
And of course HeaderText="xxx" must match the column names from the database that are stored in the DataTable.

what is the command of select in grid view asp.net

I have a GridView called gridview1
What I want is that if the user select or click on specific row some action will happen.
For example I want to get the value from that row and store it in a new variable.
How can I do it? I'm confused about what I should do to get the value?
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string stuId = ?
}
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<u>Selected Row Values: </u>
<br />
<br />
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
//Accessing BoundField Column
string name = GridView1.SelectedRow.Cells[0].Text;
//Accessing TemplateField Column controls
string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;
lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}
you simply copy and paste your issue is resolve.
you could use like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
OnRowCommand = "OnRowCommand">
<Columns>
<asp:ButtonField CommandName = "ButtonField" DataTextField = "StudID"
ButtonType = "Button"/>
</Columns>
</asp:GridView>
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}

Why doesn't radio button work?

I am using radio button inside gridivew. I want to select 1 radio button at a time not multiple. I tried this but not working i.e it disables the only selected one too.
protected void btnAward_CheckedChanged(object sender, EventArgs e)
{
try
{
foreach (GridViewRow gr in gvAppliedWorks.Rows)
{
int RowIndex = gr.RowIndex;
int AppliedWorkID = gvAppliedWorks.DataKeys[gr.RowIndex].Value.ToInt32();
RadioButton rdbtn = gr.FindControl("btnAward") as RadioButton;
if (rdbtn.Checked == true)
{
//if(RowIndex )
rdbtn.Checked = false;
}
}
}
catch (Exception ex)
{
Utility.Msg_Error(Master, ex.Message);
}
}
}
Try this code:
GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton runat="server" id="rbtn1" name="rbtn" GroupName="rgrp" onclick = "RadioCheck(this);" ></asp:RadioButton>
<asp:HiddenField ID="HiddenField1" runat="server" Value = '<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code for filling gridview from DB
protected void bind()
{
using (SqlConnection con = new SqlConnection("Connection string"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tableName", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
}
}
Finally add this script to avoid multiple selection
<script type = "text/javascript">
function RadioCheck(rb) {
var gv = document.getElementById("<%=GridView1.ID%>");
var rbs = gv.getElementsByTagName("input");
var row = rb.parentNode.parentNode;
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "radio") {
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
}

How to Keep row values in gridview after adding new row?

I have a gridview with textboxes for item no, desc qty, cost, extncost. When itemno entered in the textbox desc and cost of the item will comes automatically by on textbox event change.
Here when i add a new row in the grid view, values of last entered value got disappears.
when i am checking using break point i can able to see the last entered values in data table.
Since, while adding new row has blank text boxes, now system considers blank text box for on text change event. So, last entered values also not displaying. Text box changes in one row also affects in other rows.
Here is the ASPX.page code:
<asp:UpdatePanel ID="gin_pnlupdt" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView ID="grv_gindet" runat="server" ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="grvStudentDetails_RowDeleting"
OnRowDataBound="grv_gindtrowcmd" OnRowCommand="grv_gindetrowcmd">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="SNo" />
<asp:TemplateField HeaderText="Item Number">
<ItemTemplate>
<asp:TextBox ID="txt_itemno" runat="server" OnTextChanged="txt_itemno_changed" AutoPostBack="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description">
<ItemTemplate>
<asp:Label ID="txt_itemdesc" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txt_qty" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Cost">
<ItemTemplate>
<asp:Label ID="txt_ucost" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Extended Cost">
<ItemTemplate>
<asp:Label ID="txt_extncost" runat="server"></asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="BtnAddRow" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="grv_gindet" />
</Triggers>
</asp:UpdatePanel>
Here is the CS code for add new row:
protected void AddNewRow()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBoxItem =
(TextBox)grv_gindet.Rows[rowIndex].Cells[1].FindControl("txt_itemno");
Label TextBoxDesc =
(Label)grv_gindet.Rows[rowIndex].Cells[2].FindControl("txt_itemdesc");
TextBox TextBoxQty =
(TextBox)grv_gindet.Rows[rowIndex].Cells[3].FindControl("txt_qty");
Label TextBoxucost =
(Label)grv_gindet.Rows[rowIndex].Cells[4].FindControl("txt_ucost");
Label TextBoxextncost =
(Label)grv_gindet.Rows[rowIndex].Cells[5].FindControl("txt_extncost");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxItem.Text;
dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxDesc.Text;
dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxQty.Text;
dtCurrentTable.Rows[i - 1]["Col4"] = TextBoxucost.Text;
dtCurrentTable.Rows[i - 1]["Col5"] = TextBoxextncost.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
grv_gindet.DataSource = dtCurrentTable;
grv_gindet.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
Code for retrive Previous data:
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox TextBoxItem = (TextBox)grv_gindet.Rows[rowIndex].Cells[1].FindControl("txt_itemno");
Label TextBoxDesc = (Label)grv_gindet.Rows[rowIndex].Cells[2].FindControl("txt_itemdesc");
TextBox TextBoxQty =
(TextBox)grv_gindet.Rows[rowIndex].Cells[3].FindControl("txt_qty");
Label TextBoxucost =
(Label)grv_gindet.Rows[rowIndex].Cells[4].FindControl("txt_ucost");
Label TextBoxextncost =
(Label)grv_gindet.Rows[rowIndex].Cells[5].FindControl("txt_extncost");
TextBoxItem.Text = dt.Rows[i]["Col1"].ToString();
TextBoxDesc.Text = dt.Rows[i]["Col2"].ToString();
TextBoxQty.Text = dt.Rows[i]["Col3"].ToString();
TextBoxucost.Text = dt.Rows[i]["Col4"].ToString();
TextBoxextncost.Text = dt.Rows[i]["Col5"].ToString();
rowIndex++;
}
}
}
}
Textbox change event:
protected void txt_itemno_changed(object sender, EventArgs e)
{
//TextBox thisTextBox = (TextBox)sender;
//GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
//int row = thisGridViewRow.RowIndex;
GridViewRow currentrow = (GridViewRow)((TextBox)sender).Parent.Parent;
TextBox thisTextBox = (TextBox)currentrow.FindControl("txt_itemno");
int row = currentrow.RowIndex;
//rowChanged[row] = true;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AWCC"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ITEMDET.ITEMDESC,RGITEMDET.UNITCOST FROM ITEMDET JOIN RGITEMDET ON RGITEMDET.ITEMNO=ITEMDET.ITEMNO WHERE ITEMDET.ITEMNO ='" + thisTextBox.Text + "' ", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
grv_gindet.Rows[row].Cells[2].Text = dr["ITEMDESC"].ToString();
grv_gindet.Rows[row].Cells[4].Text = dr["UNITCOST"].ToString();
}
}
thisTextBox.Enabled = false;
}
Postback control code for gridview child element:
protected void grv_gindtrowcmd(object sender, GridViewRowEventArgs e)
{
try
{
TextBox txtitm = e.Row.FindControl("txt_itemno") as TextBox;
LinkButton lnkbtn = e.Row.FindControl("ShowDeleteButton") as LinkButton;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(txtitm);
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(lnkbtn);
}
catch
{
}
}
protected void grv_gindetrowcmd(object sender, GridViewCommandEventArgs e)
{
try
{
Button btnad = grv_gindet.FooterRow.FindControl("ButtonAdd") as Button;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(btnad);
}
catch
{
}
}
Kinldy provide a solution ASAP, do the needful.
I hope this will help you, change this in Textchange event
GridViewRow currentrow = (GridViewRow)((TextBox)sender).Parent.Parent.Parent.Parent;
TextBox thisTextBox = (TextBox)currentrow.FindControl("txt_itemno");
if (!string.IsNullOrWhiteSpace(thisTextBox.Text))
{
int row = currentrow.RowIndex;
//rowChanged[row] = true;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AWCC"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ITEMDET.ITEMDESC,RGITEMDET.UNITCOST FROM ITEMDET JOIN RGITEMDET ON RGITEMDET.ITEMNO=ITEMDET.ITEMNO WHERE ITEMDET.ITEMNO ='" + thisTextBox.Text + "' ", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
((Label)(grv_gindet.Rows[row].FindControl("txt_itemdesc"))).Text = dr["ITEMDESC"].ToString();
((TextBox)(grv_gindet.Rows[row].FindControl("txt_ucost"))).Text = dr["UNITCOST"].ToString();
}
con.Close();
}
thisTextBox.Enabled = false;
}

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