dynamic textboxes on dropdown's selectedindex - asp.net

I want to create 5 text boxes created on drop down selected index change and 4 text boxes created if dropdown index is 4. dropdown is inside asp.net updatepanel. There is a button as well inside update panel. When user will click that button, whatever is typed in textboxes, is shown on label.
Please suggest me solution.

May this work
<div>
</div><asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Panel ID="Panel1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
onselectedindexchanged="DropDownList1_SelectedIndexChanged"><asp:ListItem Value="1">one </asp:ListItem><asp:ListItem Value="2">Two </asp:ListItem><asp:ListItem Value="3">Three </asp:ListItem><asp:ListItem Value="4">Four</asp:ListItem>
</asp:DropDownList>
<br />
<asp:Button ID="Button2" runat="server" Text="fectchText" onclick="Button2_Click" />
<br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ContentTemplate>
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (ViewState["mode"].ToString() == "1")
createTextbox();
ViewState.Add("mode", "1");
}
else
{
ViewState.Add("mode", "0");
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
createTextbox();
}
public void createTextbox()
{
int noOftextbox = Convert.ToInt32(DropDownList1.SelectedItem.Value);
for (int i = 0; i < noOftextbox; i++)
{
TextBox txtbox = new TextBox();
txtbox.ID = "txt" + i;
txtbox.Visible = true;
txtbox.Height = 30;
txtbox.Width = 100;
UpdatePanel1.ContentTemplateContainer.Controls.Add(txtbox);
PlaceHolder1.Controls.Add(txtbox);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
int nocount= Convert.ToInt32(DropDownList1.SelectedItem.Value);
for (int count = 0; count <= nocount-1 ; count++)
{
TextBox txtRead = (TextBox)PlaceHolder1.FindControl("txt" + (count));
Label1.Text += txtRead.Text+"-";
}
}

You can try this.....
for (int i = 0; i < ddlTest.SelectedIndex; i++)
{
TextBox txt = new TextBox();
txt.ID = "txt" + i.ToString();
PlaceHolder1.Controls.Add(txt);
}
Change ddlTest.SelectedIndex to your loop condition.....

Hers the solution create txtbox inside updatepanel
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Panel ID="Panel1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="False">
<asp:ListItem Value="1">one </asp:ListItem><asp:ListItem Value="2">Two </asp:ListItem><asp:ListItem Value="3">Three </asp:ListItem><asp:ListItem Value="4">Four</asp:ListItem>
</asp:DropDownList>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
protected void Button1_Click(object sender, EventArgs e)
{
int noOftextbox =Convert.ToInt32(DropDownList1.SelectedItem.Value);
for (int i = 0; i < noOftextbox; i++)
{
TextBox txtbox = new TextBox();
txtbox.ID = i.ToString();
txtbox.Visible = true;
txtbox.Height = 30;
txtbox.Width = 100;
txtbox.Text = "txt" + i.ToString();
PlaceHolder1.Controls.Add(txtbox);
//UpdatePanel1.Controls.Add(txtbox);
//UpdatePanel1.Controls.Add(new LiteralControl("<br/>"));
}
}

You Can try this...
//Add Control into Panel
for (int i = 0; i < 5; i++)
{
TextBox txt = new TextBox();
txt.ID = "txt" + i.ToString();
txt.Text = "this is text:" + i.ToString();
pnlTest.Controls.Add(txt);
}
//Fetch Value from Panel
for (int i = 0; i < pnlTest.Controls.Count; i++)
{
string val = ((TextBox)pnlTest.Controls[i]).Text;
}
First loop for add dynamic control into panel and another loop for fetch value from control....

Related

RadGrid: Get the modified Items on edit

On a RadGrid I can use the CommandItemTemplate to define my own buttons for, in my case, Save and Cancel the edit (like below)
<CommandItemTemplate>
<div style="padding: 5px 5px;">
<asp:LinkButton ID="btnUpdateEdited" runat="server" CommandName="UpdateEdited">Update</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server" CommandName="CancelAll">Cancel editing</asp:LinkButton>
</div>
</CommandItemTemplate>
On the code behind, I set up the ItemCommand.
> protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName.CompareTo("UpdateEdited") == 0)
{
var commandItem = ((GridCommandItem)e.Item);
//Updade code here.
}
}
How can I access the modified row with the modified fields so I can perform an updade?
You should have them in command item and you can access them like this:
GridDataItem item = (GridDataItem)e.Item;
string value = item["ColumnUniqueName"].Text;
Is this what you want ? Just a sample you might need to modify it..
.aspx
<telerik:RadGrid ID="rg" runat="server" AutoGenerateColumns="false"
OnNeedDataSource="rg_NeedDataSource" OnItemCommand="rg_ItemCommand"
MasterTableView-CommandItemDisplay="Top" OnItemDataBound="rg_ItemDataBound">
<MasterTableView EditMode="InPlace">
<CommandItemTemplate>
<div style="padding: 5px 5px;">
<asp:LinkButton ID="btnUpdateEdited" runat="server"
CommandName="UpdateEdited">Update</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server"
CommandName="CancelAll">Cancel editing</asp:LinkButton>
</div>
</CommandItemTemplate>
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Label ID="lbl" runat="server"
Text='<%# Eval("A") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt" runat="server"
Text='<%# Eval("A") %>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Text="Edit"
CommandName="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate> </EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("A");
dt.Rows.Add("A1");
// Check & Bind
if (dt != null)
{
// Viewstate
ViewState["Data"] = dt;
rg.DataSource = dt;
rg.DataBind();
dt.Dispose();
}
}
}
protected void rg_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
rg.DataSource = ViewState["Data"] as DataTable;
}
protected void rg_ItemCommand(object sender, GridCommandEventArgs e)
{
// Check
if (e.CommandName == "UpdateEdited")
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("A");
// Loop All
foreach (GridEditableItem item in rg.Items)
{
// Find Control
TextBox txt = item.FindControl("txt") as TextBox;
// Check & Add to DataTable
if (txt != null) dt.Rows.Add(txt.Text.Trim());
}
// Check
if (dt != null && dt.Rows.Count > 0)
{
// Set Viewstate
ViewState["Data"] = dt;
// Bind
rg.DataSource = dt;
rg.DataBind();
// Dispose
dt.Dispose();
}
}
else if (e.CommandName == "CancelAll")
{
// Clear Edit Mode
rg.MasterTableView.ClearChildEditItems();
// Rebind
rg.Rebind();
}
}
protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
// Check
if (e.Item is GridCommandItem)
{
// Find Control
LinkButton btnUpdateEdited = e.Item.FindControl("btnUpdateEdited") as LinkButton;
LinkButton btnCancel = e.Item.FindControl("btnCancel") as LinkButton;
// Get is Edit Mode ?
if (rg.EditIndexes.Count > 0)
{
if (btnUpdateEdited != null) btnUpdateEdited.Visible = true;
if (btnCancel != null) btnCancel.Visible = true;
}
else
{
if (btnUpdateEdited != null) btnUpdateEdited.Visible = false;
if (btnCancel != null) btnCancel.Visible = false;
}
}
}

Failed to load viewstate - dynamic controls in ASP.NET

I have read many articles on viewstate but I can't get my head around it.
Basically I want to have two listboxes with add and remove buttons and a Proceed button.
When the Proceed button is pressed, the previous is hidden and a textbox is presented for each item in the first list box with 2 drop down boxes to describe it + a textbox for each item in the second list box (also for the user to add a description).
I then want a Finalise Button to save all this information to a database.
So far I have the following code:
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
CreateDynamicControls();
Page.MaintainScrollPositionOnPostBack = true;
Build2.Visible = false;
Build3.Visible = false;
Build4.Visible = false;
Finish.Visible = false;
}
void AddC_Click(Object sender, EventArgs e)
{
criteria.Items.Add(addnewc.Text.ToString());
addnewc.Text = null;
}
void RemoveCriterion_Click(Object sender, EventArgs e)
{
for (int i = 0; i < criteria.Items.Count; i++)
{
if (criteria.Items[i].Selected)
{
criteria.Items.Remove(criteria.Items[i]);
i--;
}
}
}
void AddAlternative_Click(Object sender, EventArgs e)
{
alternatives.Items.Add(addnewa.Text.ToString());
addnewa.Text = null;
}
void RemoveAlternative_Click(Object sender, EventArgs e)
{
for (int i = 0; i < alternatives.Items.Count; i++)
{
if (alternatives.Items[i].Selected)
{
alternatives.Items.Remove(alternatives.Items[i]);
i--;
}
}
}
void Continue_Click(Object sender, EventArgs e)
{
Build1.Visible = false;
Build2.Visible = true;
Build3.Visible = true;
CreateDynamicControls();
Finish.Visible = true;
}
void CreateDynamicControls()
{
Build2.Controls.Clear();
Build3.Controls.Clear();
Build2.Controls.Add(new LiteralControl("<h3>Please define each criterion.</h3><p>By describing it and indicating if it is 1/2 and a/b.</p>"));
for (int i = 0; i < criteria.Items.Count; i++)
{
Build2.Controls.Add(new LiteralControl("<strong>" + criteria.Items[i].Text + "</strong> Description:<br />"));
TextBox criteriondesc = new TextBox();
Build2.Controls.Add(criteriondesc);
criteriondesc.ID = "c" + i.ToString();
criteriondesc.Rows = 3;
criteriondesc.Width = 850;
criteriondesc.TextMode = TextBoxMode.MultiLine;
Build2.Controls.Add(new LiteralControl("<br />"));
Build2.Controls.Add(new LiteralControl("Desc1: "));
DropDownList aim = new DropDownList();
aim.ID = i.ToString();
aim.Width = 250;
aim.Items.Add(new ListItem("1"));
aim.Items.Add(new ListItem("2"));
Build2.Controls.Add(aim);
Build2.Controls.Add(new LiteralControl(" Desc2: "));
DropDownList source = new DropDownList();
source.ID = i.ToString();
source.Width = 250;
source.Items.Add(new ListItem("a"));
source.Items.Add(new ListItem("b"));
Build2.Controls.Add(source);
Build2.Controls.Add(new LiteralControl("<br /><br />"));
}
Build3.Controls.Add(new LiteralControl("<h3>Please define each alternative.</h3><p>Please describe each alternaitve in detail.</p>"));
for (int i = 0; i < alternatives.Items.Count; i++)
{
Build3.Controls.Add(new LiteralControl("<strong>" + alternatives.Items[i].Text + "</strong> Description:<br />"));
TextBox altdesc = new TextBox();
altdesc.ID = "a" + i.ToString();
altdesc.Rows = 3;
altdesc.Width = 850;
altdesc.TextMode = TextBoxMode.MultiLine;
Build3.Controls.Add(altdesc);
Build3.Controls.Add(new LiteralControl("<br />"));
}
Build3.Controls.Add(new LiteralControl("<br /><h3>Review dates.</h3><p>Please select a date for a meeting.</p>"));
OboutInc.Calendar2.Calendar selectdates = new OboutInc.Calendar2.Calendar();
Build3.Controls.Add(selectdates);
}
void Finish_Click(Object sender, EventArgs e)
{
Build4.Visible = true;
foreach (var control in Build2.Controls)
{
if (control.GetType() == typeof(TextBox))
{
Build4.Controls.Add(new LiteralControl(((TextBox)control).Text + "<br>"));
}
}
foreach (var control in Build3.Controls)
{
if (control.GetType() == typeof(TextBox))
{
Build4.Controls.Add(new LiteralControl(((TextBox)control).Text + "<br>"));
}
}
}
</script>
<asp:Content runat="server" ID="MainContent" ContentPlaceHolderID="MainContent">
<asp:Panel ID="Build1" runat="server">
<h3>What is your aim?</h3>
<p>
<asp:TextBox ID="goal" runat="server" Width="850px"></asp:TextBox>
</p>
<h3>What are the criteria of your decision?</h3>
<p>
<asp:ListBox ID="criteria" runat="server" Rows="8" Width="850px"></asp:ListBox><br />
<asp:Button ID="RemoveCriterion" runat="server" Text="Remove" OnClick="RemoveCriterion_Click" />
<asp:TextBox ID="addnewc" runat="server" Width="650px"></asp:TextBox>
<asp:Button ID="AddC" runat="server" Text="Add" OnClick="AddC_Click" />
</p>
</p>
<h3>What are the alternatives of your decision?</h3>
<p>
<asp:ListBox ID="alternatives" runat="server" Rows="8" Width="850px"></asp:ListBox><br />
<asp:Button ID="RemoveAlternative" runat="server" Text="Remove" OnClick="RemoveAlternative_Click" />
<asp:TextBox ID="addnewa" runat="server" Width="650px"></asp:TextBox>
<asp:Button ID="AddAlternative" runat="server" Text="Add" OnClick="AddAlternative_Click" />
</p>
<p align="right"><asp:Button ID="continue" runat="server" Text="Continue" OnClick="Continue_Click" /></p>
</asp:Panel>
<asp:Panel ID="Build2" runat="server">
</asp:Panel>
<asp:Panel ID="Build3" runat="server">
</asp:Panel>
<asp:Panel ID="Build4" runat="server">
</asp:Panel>
<p align="right"><asp:Button ID="Finish" runat="server" Text="Finish" OnClick="Finish_Click" /></p>
</asp:Content>
As you can see, at the minute I am just trying to output the user's text from the dynamically created textbox fields.
However, I am getting the error
Failed to load viewstate. The control tree into which viewstate is
being loaded must match the control tree that was used to save
viewstate during the previous request. For example, when adding
controls dynamically, the controls added during a post-back must match
the type and position of the controls added during the initial
request.
at: Line 169: Build3.Controls.Add(altdesc);
Does anyone know how to fix this problem with the viewstate?
I am very new to ASP.NET, my background is mainly in WinForms.
Thank you for any help and advice!!
You are creating your controls too late. You should create them during the Init events of the page, and not Page Load. I suggest You read abit about page life cycle
I think the best way to do it, it would be :
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
CreateDynamicControls();
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
CreateDynamicControls();<br/>
}
Small sample:
http://class10e.com/Microsoft/which-method-should-you-add-to-the-web-page
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

Disable the Edit button on all the rows when Edit button is clicked on a particular row in GridView

I have a gridView with 5 columns with Edit and Delete button on each row of GridView. Once an Edit button a particular row is clicked , I want to disable the edit and delete buttons on rest of the rows.
Below is my aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowFooter="True" EnableModelValidation="True" onrowdatabound="GridView1_RowDataBound" onrowcommand="GridView1_RowCommand" onrowdeleting="GridView1_RowDeleting" EditRowStyle-ForeColor="Aqua" onrowediting="GridView1_RowEditing" >
<asp:TemplateField HeaderText="Item#" >
<ItemTemplate>
<asp:Label ID="Item#" runat="server" Text='Label' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
..........
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" CausesValidation ="false" Font-Size="Smaller" CommandName="Edit" Text="Edit" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' Width="35px"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" CssClass="GridButton" CausesValidation="False" CommandName="Delete" Font-Size="Smaller" Text="Delete" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int x = Convert.ToInt32(e.CommandArgument.ToString());
txtLineItemNumber.Text = (x + 1).ToString();
}
else
{
int x = Convert.ToInt32(e.CommandArgument.ToString());
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowIndex != x)
{
Button editButton = (Button)row.FindControl("btnEdit");
editButton.Enabled = false;
Button deleteButton = (Button)row.FindControl("btnDelete");
deleteButton.Enabled = false;
}
else
{
Button deleteButton = (Button)row.FindControl("btnDelete");
deleteButton.Text = "Cancel";
e.CommandName = "Cancel"; --- This is not possible...what should I do so that the Command Name is changed to Cancel and it does the cancel operation.
}
} }
}
Please help me to get it working.....
The approach you are taking will work fine. However the CommandArgument which is set in your markup CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' is not a reference to the Button itsself but the index of the GridView row the Button resides in.
You will need to retrieve the index from the CommandArgument in the RowCommand event and then enable/disable all buttons on other rows like so:
void gridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
case "edit":
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
foreach (GridViewRow row in gridView1.Rows)
{
if (row.RowIndex != rowIndex)
{
Button editButton = (Button)row.FindControl("btnEdit");
editButton.Enabled = false;
Button deleteButton = (Button)row.FindControl("btnDelete");
deleteButton.Enabled = false;
}
}
}break;
}
}
Edit (based on comment)
Try moving the code that modifies the delete button to the RowEditing event handler like so:
void gridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
gridView1.EditIndex = e.NewEditIndex;
DataBind();
Button deleteButton = (Button)gridView1.Rows[e.NewEditIndex].FindControl("btnDelete");
deleteButton.Text = "Cancel";
deleteButton.CommandName = "Cancel";
}
void gridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridView1.EditIndex = -1;
DataBind();
}
Hope this helps.
You could use javascript, outlined here, http://www.krissteele.net/blogdetails.aspx?id=92 . Add logic to not disable for the current row.

GridView strange behaviour

I have problem on page bellow, in gdvCar_DataBound I add three buttons, when I click on any of them, page go to postback but doesn't enter in gdvCar_RowCommand and then that buttons ( and images that I also add in gdvCar_DataBound) disaper. Grid is then full like gdvCar_DataBound isn't execute. My question is why it doesn't enter at gdvCar_RowCommand ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HMS.library;
using System.Data.SqlClient;
namespace HMS
{
public partial class Cars : System.Web.UI.Page
{
#region fields
private const Int16 PageId = 1;
private String connectionString = "Server=localhost;Database=hms_test;Trusted_Connection=True;";
String[] filters = null;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillProducer();
FillModel(Convert.ToInt16(ddlProducer.SelectedValue));
RestoreFilters();
FillGrid();
}
}
#region events
protected void ddlProducer_Changed(object sender, EventArgs e)
{
if (ddlProducer.SelectedValue != "0")
{
ddlModel.Enabled = true;
FillModel(Convert.ToInt16(ddlProducer.SelectedValue));
}
else
{
ddlModel.SelectedValue = "0";
ddlModel.Enabled = false;
}
upSearch.Update();
}
protected void gdvCar_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Reserve":
{
pnlReserve.Visible = true;
break;
}
case "Phone":
{
break;
}
case "Email":
{
break;
}
}
}
protected void gdvCar_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String id = e.Row.Cells[0].Text;
Image img = new Image();
img.ID = "img_one" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[7].Text;
e.Row.Cells[7].Controls.Add(img);
img = new Image();
img.ID = "img_two" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[8].Text;
e.Row.Cells[8].Controls.Add(img);
img = new Image();
img.ID = "img_three" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[9].Text;
e.Row.Cells[9].Controls.Add(img);
ImageButton imbReserve = new ImageButton();
imbReserve.ID = "res" + id;
imbReserve.Enabled = true;
imbReserve.Width = 48; imbReserve.Height = 48;
imbReserve.ToolTip = "Reserve"; imbReserve.AlternateText = "Reserve";
imbReserve.ImageUrl = "images/icons/key.gif";
imbReserve.CommandName = "Reserve";
imbReserve.CommandArgument = id;
e.Row.Cells[10].Controls.Add(imbReserve);
ImageButton imbPhone = new ImageButton();
imbPhone.ID = "phone" + id;
imbPhone.Enabled = true;
imbPhone.Width = 48; imbPhone.Height = 48;
imbPhone.ToolTip = "Reserve by phone"; imbPhone.AlternateText = "Phone";
imbPhone.ImageUrl = "images/icons/phone.jpg";
imbPhone.CommandName = "Phone";
imbPhone.CommandArgument = id;
e.Row.Cells[11].Controls.Add(imbPhone);
ImageButton imbEmail = new ImageButton();
imbEmail.ID = "email" + id;
imbEmail.Enabled = true;
imbEmail.Width = 48; imbEmail.Height = 48;
imbEmail.ToolTip = "Reserve by email"; imbEmail.AlternateText = "Email";
imbEmail.ImageUrl = "images/icons/email.jpg";
imbEmail.CommandName = "Email";
imbEmail.CommandArgument = id;
e.Row.Cells[12].Controls.Add(imbEmail);
}
}
protected void imbSearch_Click(object sender, ImageClickEventArgs e)
{
StoreFilters();
FillGrid();
}
#endregion
#region functions
private void FillProducer()
{
hmsDataContext hms = new hmsDataContext();
var source = from o in hms.producer_cars
orderby o.name
select new
{
o.id,
o.name
};
foreach (var temp in source)
ddlProducer.Items.Add(new ListItem(temp.name, temp.id.ToString()));
ddlProducer.Items.Insert(0, (new ListItem("all producers", "0")));
}
private void FillModel(int producer_id)
{
hmsDataContext hms = new hmsDataContext();
var source = from o in hms.model_cars
from p in hms.producer_cars
where o.producer_car_id == producer_id && p.id == producer_id
orderby o.name
select new
{
o.id,
o.name
};
ddlModel.Items.Clear();
foreach (var temp in source)
ddlModel.Items.Add(new ListItem(temp.name, temp.id.ToString()));
ddlModel.Items.Insert(0, (new ListItem("all producers", "0")));
}
private void FillGrid()
{
SqlConnection conn = new SqlConnection(connectionString);
String command = #"SELECT car.id AS id, car.price as price, car.weight as weight,
car.year as year, producer_car.name as producer, model_car.name as model, car.number_seats as number_seats, car.photo_one as photo_one,car.photo_two as photo_two,car.photo_three as photo_three, '' as reserver,'' as phone,'' as email
FROM car INNER JOIN model_car on car.model_car_id=model_car.id
INNER JOIN producer_car on model_car.producer_car_id=producer_car.id";
if(filters!=null){
String[] search=new String[5];
search[0]=filters[0]!="0"?"producer_car.id="+filters[0]:"";
search[1]= filters[1] != "0" ? "model_car.id=" + filters[1] : "";
search[2]=filters[2]!=""?"car.color LIKE \'"+filters[2]+"\'":"";
search[3]=filters[3]!=""?"car.price<"+filters[3]:"";
search[4] = filters[4] != "" ? "car.number_seats=" + filters[4] : "";
var a=from f in search
where f!=""
select f;
String filterAddition="";
if(a.Count()>0){
filterAddition=" WHERE ";
foreach ( var b in a){
filterAddition+=" "+b+" AND";
}
filterAddition=filterAddition.EndsWith("AND")?filterAddition.Substring(0,filterAddition.Length-3):filterAddition;
}
command+=filterAddition;
}
SqlCommand comm = new SqlCommand(command, conn);
SqlDataReader r = null;
try
{
comm.Connection.Open();
r =comm.ExecuteReader();
gdvCar.DataSource = r;
gdvCar.DataBind();
r.Close();
}
catch (Exception exc)
{
throw (exc);
}
finally
{
conn.Close();
}
}
private void StoreFilters()
{
filters = new String[5];
filters[0] = ddlProducer.SelectedValue;
filters[1] = ddlModel.SelectedValue;
filters[2] = ddlColor.SelectedValue;
filters[3] = txtStartPrice.Text;
filters[4] = ddlNumber.SelectedValue;
Session["1"] = filters;
}
private void RestoreFilters()
{
if (Session["1"] != null)
{
filters = (String[])Session["1"];
ddlProducer.SelectedValue = filters[0];
ddlProducer_Changed(null, null);
ddlModel.SelectedValue = filters[1];
ddlColor.SelectedValue = filters[2];
txtStartPrice.Text = filters[3];
ddlNumber.SelectedValue = filters[4];
}
}
private void ReserveCar(String FirstName, String LastName, DateTime Start, DateTime End, String Visa, Int16 CarId)
{
hmsDataContext hms = new hmsDataContext();
var a = from c in hms.cars
from rc in hms.rented_cars
where c.id == rc.id_car && c.id == CarId
select new
{
start = rc.start,
end = rc.end
};
Boolean free = false;
if (a.Count() == 0)
{
free = true;
}
else if (a.Count() == 1)
{
if ((a.First().start > End) || (a.First().end < Start))
free = true;
}
else
{
if ((a.First().start > End) || (a.First().end < Start))
free = true;
else if(!free)
{
int n = a.Count();
for (int i = 0; (i < n - 1) && (!free); i++)
{
if (a.ElementAt(i).end < Start && a.ElementAt(i + 1).start > End)
free = true;
i++;
}
if (!free)
{
if (a.ElementAt(n - 1).end < Start)
free = true;
}
}
}
if (free)
{
//insert
}
else
{
//label-nije slobodno za taj termin
}
}
#endregion
}
}
aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Cars.aspx.cs" Inherits="HMS.Cars"
MasterPageFile="~/frame.Master" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ContentPlaceHolderID="content" ID="con" runat="server">
<link rel="StyleSheet" href="css/menu.css" type="text/css" media="all">
<asp:ScriptManager ID="sc" runat="server">
</asp:ScriptManager>
<div id="menu">
<ul class="glossymenu">
<li><b>Home</b></li>
<li class="current"><b>Cars</b></li>
<li><b>Boats</b></li>
<li><b>Contact</b></li>
<li><b>Admin</b></li>
</ul>
</div>
<div>
<div>
<asp:UpdatePanel ID="upSearch" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="search">
<fieldset>
<legend>Advanced search</legend>
<table>
<tr>
<td>
Proizvođač:<asp:DropDownList ID="ddlProducer" runat="server" OnSelectedIndexChanged="ddlProducer_Changed"
AutoPostBack="true">
</asp:DropDownList>
</td>
<td>
Model:<asp:DropDownList ID="ddlModel" runat="server" Enabled="false">
</asp:DropDownList>
</td>
<td>
Boja:<asp:DropDownList ID="ddlColor" runat="server">
<asp:ListItem Text="all" Value=""></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
Cena do:
<asp:TextBox ID="txtStartPrice" runat="server" MaxLength="10"></asp:TextBox>
din/dan
</td>
<td>
Number seats:<asp:DropDownList ID="ddlNumber" runat="server">
<asp:ListItem Text="-- --" Value=""></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
<asp:ListItem Text="4" Value="4"></asp:ListItem>
<asp:ListItem Text="5" Value="1"></asp:ListItem>
<asp:ListItem Text="6" Value="2"></asp:ListItem>
<asp:ListItem Text="7" Value="3"></asp:ListItem>
<asp:ListItem Text="8" Value="4"></asp:ListItem>
<asp:ListItem Text="9" Value="2"></asp:ListItem>
<asp:ListItem Text="10" Value="3"></asp:ListItem>
<asp:ListItem Text="11" Value="4"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:ImageButton ID="imbSearch" runat="server" ImageUrl="images/icons/search.png"
Width="32" Height="32" ToolTip="Search by choosen criterions" AlternateText="Search"
OnClick="imbSearch_Click" />
</td>
</tr>
</table>
</fieldset>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<br />
<div>
<asp:UpdatePanel ID="upGrid" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:GridView ID="gdvCar" runat="server" OnRowCommand="gdvCar_RowCommand"
OnRowDataBound="gdvCar_DataBound">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div>
<asp:UpdatePanel ID="upTemp" runat="server"><ContentTemplate>
<asp:Panel ID="pnlReserve" runat="server" Visible="false" Width="400" Height="400">
<asp:UpdatePanel ID="upReserve" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</ContentTemplate></asp:UpdatePanel>
</div>
</div>
</asp:Content>
You have to recreate the buttons in RowCreated on every Postback, otherwise their events won't fire.
Save what you need in RowDataBound in the ViewState. In the RowCreated recreate them on Postback(RowDatabound will only be called on Databinding) based on the Viewstate value. Then all controls are available in early page-lifecyle to raise their events.
I believe you can do it in a more elegant way, take a look,
<asp:GridView ...>
<Columns>
<asp:BoundField HeaderText="Some Caption" DataField="Column name from the DataReader result"/>
...
<asp:TemplateField HeaderText="Image..">
<asp:Image runat="server" ImageUrl='<%# String.Format("images/car/{0}", Eval("The column name from the DataReader of the cell 7") %>' />
</asp:TemplateField>
<asp:TemplateField HeaderText="ImageButton..">
<asp:ImageButton runat="server" .../>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then you don't have to add the buttons and the images in the code and takecare of adding them each time the row is created, you just need to fetch the data from the database and set the DataSource of the gridview, and I think you can also get rid of the code fetching the data and replace it with a SqlDataSource.
Take a look at this article about the GridView,
http://msdn.microsoft.com/en-us/library/aa479353.aspx

ASP.NET - Problem with GridView with Dynamic Columns

I have a GridView that includes BoundField and TemplateField elements. Some of the TemplateField elements are dynamically generated. For the sake of reference, here is the GridView that I am using
<asp:GridView ID="myGridView" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" ShowFooter="True" EnableModelValidation="True"
OnLoad="myGridView_Load" OnRowCommand="myGridView_RowCommand"
OnRowEditing="myGridView_RowEditing" OnRowDeleting="myGridView_RowDeleting"
OnRowCancelingEdit="myGridView_RowCancelingEdit"
OnRowUpdating="myGridView_RowUpdating">
<Columns>
<asp:BoundField DataField="Number" Visible="true" HeaderText="Test" />
<asp:TemplateField HeaderText="Number">
<EditItemTemplate>
<asp:TextBox ID="tb1" runat="server" Text='<%# Bind("Number") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lb1" runat="server" Text='<%# Bind("Number") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftb" runat="server" Text="[x]" />
</FooterTemplate>
</asp:TemplateField>
<%-- Dynamically Generated Columns Will Be Inserted Here --%>
<asp:TemplateField HeaderText="Actions">
<EditItemTemplate>
<asp:LinkButton ID="ulb" runat="server" Text="update" CommandName="Update" />
<asp:LinkButton ID="clb" runat="server" Text="cancel" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="slb" runat="server" Text="insert"
OnClick="saveLinkButton_Click" />
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="elb" runat="server" Text="edit" CommandName="Edit" />
<asp:LinkButton ID="dlb" runat="server" Text="delete" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField
</Columns>
<EmptyDataTemplate>
<table border="0" cellpadding="0" cellspacing="0">
<tr><td>Number</td></tr>
<tr>
<td><asp:TextBox ID="ntb" runat="server" /></td>
<td><asp:LinkButton ID="slb2" runat="server" Text="save" OnClick="saveLinkButton_Click" /></td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
When the GridView initially loads, everything is loaded properly. However, anytime I perform a command (edit, insert, delete), all of the data goes away. Oddly, the BoundField values still appear correctly. However, any TemplateField does not seem to get rendered. The code that I am using to work with this GridView is here:
public partial class GridView : System.Web.UI.Page
{
private List<string> dynamicColumnNames = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
LoadPageData();
}
protected void saveLinkButton_Click(object sender, EventArgs e)
{
}
protected void myGridView_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
BindGridData();
}
}
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{ }
protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
myGridView.EditIndex = e.NewEditIndex;
BindGridData();
}
protected void myGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
LoadPageData();
BindGridData();
}
protected void myGridView_RowCancelingEdit(object sender, EventArgs e)
{
myGridView.EditIndex = -1;
BindGridData();
}
protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
myGridView.EditIndex = -1;
LoadPageData();
BindGridData();
}
private void BindGridData()
{
// Create a temporary data source
DataTable tempData = new DataTable();
tempData.Columns.Add("ID");
tempData.Columns.Add("Number");
// Dynamically add template columns
foreach (string columnName in dynamicColumnNames)
{
tempData.Columns.Add(columnName);
TemplateField templateField = new TemplateField();
templateField.HeaderTemplate = new MyTemplateField(ListItemType.Header, columnName);
templateField.ItemTemplate = new MyTemplateField(ListItemType.Item, columnName);
templateField.EditItemTemplate = new MyTemplateField(ListItemType.EditItem, columnName);
templateField.FooterTemplate = new MyTemplateField(ListItemType.Footer, columnName);
myGridView.Columns.Insert(2, templateField);
}
// Add some phony data
Random random = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < 10; i++)
{
DataRow tempRow = tempData.NewRow();
tempRow["Number"] = (i + 1);
foreach (string column in dynamicColumnNames)
tempRow[column] = random.NextDouble();
tempData.Rows.Add(tempRow);
}
// Bind the data to the grid
myGridView.DataSource = tempData;
myGridView.DataBind();
}
private void LoadPageData()
{
dynamicColumnNames.Add("USA");
dynamicColumnNames.Add("Japan");
dynamicColumnNames.Add("Mexico");
}
}
internal class MyTemplateField : ITemplate
{
// The type of the list item
private ListItemType listItemType;
// The value to use during instantiation
private string value1 = string.Empty;
public MyTemplateField(ListItemType listItemType, string value1)
{
this.listItemType = listItemType;
this.value1 = value1;
}
public void InstantiateIn(Control container)
{
if (listItemType == ListItemType.Item)
{
TextBox textBox = new TextBox();
textBox.ReadOnly = true;
textBox.DataBinding += new EventHandler(textBox_DataBinding);
container.Controls.Add(textBox);
}
else if (listItemType == ListItemType.EditItem)
{
TextBox textBox = new TextBox();
textBox.DataBinding += new EventHandler(textBox_DataBinding);
container.Controls.Add(textBox);
}
else if (listItemType == ListItemType.Header)
{
Literal literal = new Literal();
literal.Text = value1;
container.Controls.Add(literal);
}
else if (listItemType == ListItemType.Footer)
{
TextBox textBox = new TextBox();
container.Controls.Add(textBox);
}
}
private void textBox_DataBinding(object sender, EventArgs e)
{
TextBox textBox = (TextBox)(sender);
GridViewRow row = (GridViewRow)(textBox.NamingContainer);
textBox.Text = DataBinder.Eval(row.DataItem, value1).ToString();
}
}
How do I use commands in a GridView with Dynamically added columns? What is wrong with my code?
Thank you!
Dynamically added controls must be added on each post, you can't just add these controls on the first page load. Try removing your BindGridData() from within the Page.IsPostBack == false.

Resources