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);
}
Related
I work on asp.net web forms with c# I need to add checkbox column as last column on gridview
but i don't know how to add it
static string con =
"Data Source=DESKTOP-L558MLK\\AHMEDSALAHSQL;" +
"Initial Catalog=UnionCoop;" +
"User id=sa;" +
"Password=321;";
SqlConnection conn = new SqlConnection(con);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewSearch.DataSource = GetDataForSearch();
GridViewSearch.DataBind();
}
}
public DataTable GetDataForSearch()
{
string response = string.Empty;
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select top 10 datelogged AS EntredDatetime, Doc_type AS OrderType, Printer_name, BranchID AS BranchCode, id from Print_Report";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 50000;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
catch (Exception ex)
{
response = ex.Message;
}
finally
{
cmd.Dispose();
conn.Close();
}
return dt;
}
on aspx page
<asp:GridView ID="GridViewSearch" runat="server">
</asp:GridView>
GridViewSearch.DataSource = GetDataForSearch();
DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "X";
checkColumn.HeaderText = "X";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
GridViewSearch.Columns.Add(checkColumn);
GridViewSearch.DataBind();
I get error on line below
GridViewSearch.Columns.Add(checkColumn);
argument 1 can't convert from system.windows.forms.datagridviewcheckbox to system.web.ui.webcontrol.databoundfield
so how to solve this issue please ?
Seems to me, that if you want say a button, or check box, or dropdown?
why not just add it to the markup.
So, say like this:
<div id="MyGridPick" runat="server" style="display:normal;width:40%">
<asp:Label ID="lblSel" runat="server" Text="" Font-Size="X-Large"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" cssclass="table table-hover" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" ItemStyle-Width="120px" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Then my code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
Now, of course I get VERY tired of typing that connection string stuff over and over. So, I have a "genreal" routine like this:
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And the result of running above:
So, kind of hard to make the case to "add" a check box control, when you can just drop one into the gridview.
Same goes for a button, maybe we want a button to "view" or edit the above row, or some such.
So, once again, just drop in a plain jane button, say like this:
<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="bView" runat="server" Text="View" CssClass="btn"
OnClick="bView_Click" />
</ItemTemplate>
</asp:TemplateField>
And now we have this:
And EVEN better?
Well, since that button (or check box) is a plain jane standard control?
then you can add standard events, like a click event, or whatever you want.
Say this code for the button click (shows how to get current row).
protected void bView_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gRow = btn.NamingContainer as GridViewRow;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
DataTable dtHotel = MyRstP(cmdSQL);
General.FLoader(MyEditArea, dtHotel.Rows[0]);
MyGridPick.Style.Add("display", "none"); // hide grid
MyEditArea.Style.Add("display", "normal"); // show edit div area
}
And we now get/see this:
Edit: Process each checked/selected row.
this:
protected void cmdSelProcess_Click(object sender, EventArgs e)
{
// process all rows in GV with check box
String sPK = "";
List<int> MySelected = new List<int>();
foreach (GridViewRow gRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gRow.FindControl("chkSel");
if (chkSel.Checked)
{
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
// add pk value of row to our list
MySelected.Add(PK);
// Or we could process data based on current gRow
if (sPK != "")
sPK += ",";
sPK += PK.ToString();
Debug.Print(PK.ToString());
}
}
// at this point, we have a nice list of selected in MySelected
// or, maybe process as a data table
SqlCommand cmdSQL =
new SqlCommand($"SELECT * FROM tblHotelsA where ID IN({sPK})");
DataTable rstSelected = MyRstP(cmdSQL);
//
foreach (DataRow dr in rstSelected.Rows)
{
// do whatever
}
}
Datagridviewcheckboxcolumn is a Windows formx object. You are working in web forms. Please see the link below for information on the webforms check box field
CheckBoxField checkColumn = new CheckBoxField();
I am adding Select Checkbox at every row in GridView while loading from database. Below is my aspx page code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Width="100%" onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdatabound="GridView1_RowDataBound" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="cbSelect" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%# Eval("ID") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Part Number">
<ItemTemplate>
<asp:Label ID="lblpn" runat="server" Text='<%# Eval("PartNumber") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Part Desc">
<ItemTemplate>
<asp:Label ID="lblpd" runat="server" Text='<%# Eval("PartDesc") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I want to read the data from the rows which are selected in the respective Checkbox.
For this I have done following code in Button Click:
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow dr = GridView1.Rows[i];
Label lblID = (Label)dr.FindControl("lblid");
ID = Convert.ToInt32(lblID.Text);
CheckBox checkBox = (CheckBox)dr.FindControl("cbSelect");
if (checkBox.Checked)
{
}
}
Now if I select single row in grid then I am able to get the checkbox status Checked for that particular row.
But If I select multiple rows then I am getting only first selected row's checkbox status as checked.
From second row I am getting Check status as Unchecked. But I am able to get correct value in lblID label control.
Following is my function to fill gridview:
public void showgrid(string Location)
{
DataTable dt = new DataTable();
con.Open();
string strQuery = "";
SqlDataAdapter sda = new SqlDataAdapter();
if (chkConsiderPart.Checked)
strQuery = "select * from InventoryDetails where Status='Stocked' and ToLocation='" + Location + "' and PartNumber='" + ddlPartNumber.SelectedItem.Text + "'";
else
strQuery = "select * from InventoryDetails where Status='Stocked' and ToLocation='" + Location + "'";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
if (dt.Rows.Count == 0)
{
lblRowsStatus.Text = "No Records found for the selection.";
}
else
{
lblRowsStatus.Text = "There are " + dt.Rows.Count.ToString() + " Records found for the selection.";
}
}
I am only calling it in:
if (!IsPostBack)
{
showgrid(ddlFromLocation.SelectedItem.Text);
}
Also there was post-back at certain events of other controls. but even if I removed them same issue is happening.
Note: There is no code written in any of Gridview Events.
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
}
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.
Hello all I'm working on a little project where I'm adding controls to a page based on a SQL table of questions, this table will grow overtime. I just wanted to share the code and see if there was any better way or if any of the experts could chime in and give me any insight on future problems. Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
SqlParameter[] paramz = new SqlParameter[1];
paramz[0] = new SqlParameter("#c_id", 1);
dt = SqlHelper.ExecuteDataTable(ConfigurationManager.ConnectionStrings["sql"].ToString(), CommandType.StoredProcedure, "get_Questions", paramz);
clinicName.Text = "<b>" + dt.Rows[0]["Clinic Name"].ToString();
for(int row = 0; row <= dt.Rows.Count; row++)
{
if (row == dt.Rows.Count) //if we're on the last question put a break for spacing(this could be fixed with styling)
{
Literal alit = new Literal();
alit.Text = "<br/>";
questionsPanel.Controls.Add(alit);
}
else
{
addQuestion(dt.Rows[row], row);
}
}
}
catch (Exception err)
{
Response.Write(err.Message);
}
}
private void addQuestion(DataRow row, int i)
{
Label lbl = new Label();
lbl.Text = row["question"].ToString();
questionsPanel.Controls.Add(lbl);
Literal lit = new Literal();
lit.Text = "<br/>";
questionsPanel.Controls.Add(lit);
TextBox txt = new TextBox();
txt.ID = "txt" + i.ToString();
questionsPanel.Controls.Add(txt);
Literal lit2 = new Literal();
lit2.Text = "<br/>";
questionsPanel.Controls.Add(lit2);
}
Use a Repeater control:
ASPX Code:
<asp:Repeater id="repData" runat="server">
<ItemTemplate>
<asp:Label id="lblQuestion" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "question") %>' />
<br />
<asp:TextBox id="lblAnswer" runat="server" />
</ItemTemplate>
<FooterTemplate>
<br />
</FooterTemplate>
</asp:Repeater>
Code behind:
// Populate repeater
SqlParameter[] paramz = new SqlParameter[1];
paramz[0] = new SqlParameter("#c_id", 1);
dt = SqlHelper.ExecuteDataTable(ConfigurationManager.ConnectionStrings["sql"].ToString(), CommandType.StoredProcedure, "get_Questions", paramz);
repData.DataSource = dt;
repData.DataBind();
If the controls either use or contribute to ViewState, then you must ensure that the same controls are added to ViewState in the same order, on every post back. The order in which objects are added to ViewState depends on the order of the controls in the control tree.