Asp.Net set control that in specific row in repeater? - asp.net

repeater code:
<asp:Repeater ID="Repeater_sorular" runat="server" OnItemCommand="Repeater_sorular_ItemCommand"
OnItemDataBound="Repeater_sorular_ItemBound">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<table>
<tr>
<td>
<rad:RadChart ID="RadChart1" runat="server" DefaultType="Pie" Width="700" >
<PlotArea Appearance-FillStyle-FillType="Gradient" Appearance-FillStyle-MainColor="#D90420"
Appearance-FillStyle-SecondColor="#FFAD4A" Appearance-Border-Visible="false">
<EmptySeriesMessage>
<TextBlock Text="Seçilen anket henüz oylanmamıştır.">
<Appearance TextProperties-Font="Tahoma, 10pt, style=Bold">
</Appearance>
</TextBlock>
</EmptySeriesMessage>
</PlotArea>
<ChartTitle>
<TextBlock Appearance-TextProperties-Font="Tahoma">
</TextBlock>
</ChartTitle>
<Appearance ImageQuality="HighQuality" Border-Color="#DFDDDD" TextQuality="ClearTypeGridFit">
</Appearance>
<Series>
<rad:ChartSeries Type="Pie" Appearance-TextAppearance-TextProperties-Color="#FFFFFF"
Appearance-TextAppearance-TextProperties-Font="Tahoma">
</rad:ChartSeries>
</Series>
<Legend Visible="True">
<TextBlock Visible="True">
</TextBlock>
</Legend>
</rad:RadChart>
</td>
<td>
<div style="font-weight: bolder; padding: 5px;">
<%#(((RepeaterItem)Container).ItemIndex+1).ToString() %>.
<%#Eval("Subject")%>
</div>
<asp:BulletedList ID="BulletedList_secenekler" runat="server" DataSource='<%#Eval("Secenekler")%>'
DataTextField="OptionName" DataValueField="OptionId" CssClass="sira_numarali">
</asp:BulletedList>
</td>
</tr>
</table>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
repeater ItemDataBound:
protected void Repeater_sorular_ItemBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
int SurveyId = Int32.Parse(Request.QueryString["anket_id"]);
var sorular = from sr in db.TableSurveyQuestions
where sr.SurveyId == SurveyId
select sr;
//int repeater_satir = 0;
foreach (var soru in sorular)
{
RadChart RadChart1 = new RadChart();
RadChart1 = (RadChart)e.Item.FindControl("RadChart1");
ChartSeries s = RadChart1.Series.GetSeries(0);
s.Appearance.LegendDisplayMode = ChartSeriesLegendDisplayMode.ItemLabels;
s.Clear();
s.Appearance.ShowLabels = true;
s.Appearance.LabelAppearance.Dimensions.Margins.Bottom = 7;
s.PlotArea.IntelligentLabelsEnabled = true;
s.DataYColumn = "VoteCount";
int oy_sayisi = 0;
foreach (var secenek in soru.TableSurveyOptions)
{
int toplam_cevap_sayisi = secenek.TableSurveyVotes.Count;
int dogru_cevap_sayisi = secenek.TableSurveyVotes.Where(a => a.VoteStatus == true).Count();
double yuzde = ((double)dogru_cevap_sayisi / (double)toplam_cevap_sayisi) * 100;
ChartSeriesItem seriesItem = new ChartSeriesItem();
seriesItem.YValue = Math.Round(yuzde, 2);
seriesItem.Name = secenek.OptionName;
seriesItem.ActiveRegion.Tooltip = secenek.OptionName;
seriesItem.Label.TextBlock.Text = secenek.OptionName + " %" + Math.Round(yuzde, 2).ToString();
seriesItem.Appearance.Border.Color = Color.Silver;
seriesItem.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
s.Items.Add(seriesItem);
RadChart1.Series.Add(s);
oy_sayisi = secenek.TableSurveyVotes.Count;
}
RadChart1.ChartTitle.TextBlock.Text = db.TableSurveyQuestions.Where(a => a.SurveyId == SurveyId).FirstOrDefault().TableSurvey.Title;
RadChart1.Legend.TextBlock.Text = "Toplam : " + oy_sayisi + " Oy ";
//repeater_satir++;
}
}
}
when I write this code, all charts are showing the last object values. I want to set each chart with different data.
How can I do this.
Thanks.

You could use the ItemIndex property
<asp:Repeater runat="server" ID="myRepeater" OnItemDataBound="myRepeater_ItemDataBound">
<ItemTemplate>
<asp:Label Text='<%# Eval("Id") %>' runat="server" ID="myRepeaterLabel" />
</ItemTemplate>
</asp:Repeater>
Code behind:
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
switch (e.Item.ItemIndex)
{
case 3:
Label l = (Label)e.Item.FindControl("myRepeaterLabel");
l.Text += "whatever";
break;
default:
break;
}
}
}
Output:
Edited
I am not sure if this would help but you should bind your repeater like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindRepeater();
}
}
private void BindRepeater()
{
var r = Builder<Product>.CreateListOfSize(20).Build();
this.myRepeater.DataSource = r;
this.myRepeater.DataBind();
}
And just modify specific values already bindded in the ItemDataBound event

Related

Getting values of my childRepeater

I have 2 repeaters where the first one list the questions and the second one list multiple choice for that specific question.
However, there are some multiple choice(input type="radio") or Text(input type="text") anwers. Im trying to get the value of either one(radio) or the other(text).
<%# DataBinder.Eval(Container.DataItem,"Descricao")%>
<%-- Listagem de Respostas --%>
<asp:Repeater ID="uxRespList" runat="server" OnItemDataBound="uxRespList_ItemDataBound" OnItemCommand="uxRespList_ItemCommand">
<ItemTemplate>
<tr>
<td>
<div id="uxRespostaText" visible="false" runat="server">
<input type="text" id="uxRespostaDissertativa" placeholder="Resposta" style="width:1000px" ></input>
</div>
<div id="uxRespostaRadio" visible="false" runat="server">
<input type="radio" id="uxResposta" runat="server" value='<%# DataBinder.Eval(Container.DataItem, "Descricao")%>'/><%# DataBinder.Eval(Container.DataItem, "Descricao")%>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
Code Behind
protected void uxQuestList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater rptRespostas = (Repeater)(e.Item.FindControl("uxRespList"));
QuestionarioPergunta pergunta = (QuestionarioPergunta)e.Item.DataItem;
rptRespostas.DataSource = ctx.QuestionarioRespostas.Where(x => x.PergId == pergunta.Id).ToList();
PergId.Text = pergunta.Id.ToString();
rptRespostas.DataBind();
}
}
protected void uxRespList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Web.UI.HtmlControls.HtmlContainerControl uxRespostaText = (System.Web.UI.HtmlControls.HtmlContainerControl)e.Item.FindControl("uxRespostaText");
System.Web.UI.HtmlControls.HtmlContainerControl uxRespostaRadio = (System.Web.UI.HtmlControls.HtmlContainerControl)e.Item.FindControl("uxRespostaRadio");
int PerguntaID = Int32.Parse(PergId.Text);
var pergunta = ctx.QuestionarioPerguntas.Where(x => x.Id == PerguntaID).FirstOrDefault();
if (pergunta.TipoPergunta == "Dissertativa")
{
uxRespostaText.Visible = true;
}
else
{
uxRespostaRadio.Visible = true;
}
}
}
//Save here
protected void uxSalvarPesquisa_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in uxRespList.Items)
{
}
}
You can get values of your html input as below and based on your requirement you can modify the code.
foreach (RepeaterItem item in uxQuestList.Items)
{
Repeater uxRespList = (Repeater)item.FindControl("uxRespList");
foreach (RepeaterItem inneritem in uxRespList.Items)
{
HtmlInputText input = (HtmlInputText)inneritem.FindControl("uxRespostaDissertativa");
if (input.Attributes["visible"] == "true")
{
var answer = input.Value;
}
HtmlInputRadioButton inputRadio = (HtmlInputRadioButton)inneritem.FindControl("uxRespostaRadio");
if (inputRadio.Attributes["visible"] == "true")
{
var answer = inputRadio.Value;
}
}
}

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

How to refresh 2 repeater in asp.net

I'm building a social network in asp. I code main page has post status and comment after each status using repeater control, but when I click on 'Post' button and 'Comment' button the repeater control not refresh. I mush logout and login again to display new status and new comment. How can I solve this problem:
MainPage.aspx
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h2>Hello</h2>
<asp:Label ID="lblUser" runat="server" Text=""></asp:Label>
<asp:Label ID="lblID" runat="server" Text=""></asp:Label>
<hr />
<asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btnPost" runat="server" Text="Post" OnClick="btnPost_Click" />
<hr />
<asp:Repeater ID="repeater" runat="server" OnItemDataBound="repeater_ItemDataBound">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="labelID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Mess_Id") %>'></asp:Label>
<li><%#DataBinder.Eval(Container.DataItem, "Message")%></li>
<asp:Repeater ID="repeatComment" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
<ItemTemplate>
<li>
<%#DataBinder.Eval(Container.DataItem, "Comments")%>
</li>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:TextBox ID="txtComment" runat="server"></asp:TextBox>
<asp:Button ID="btnComment" runat="server" Text="Comment" OnClick="btnComment_Click" />
<br />
</ItemTemplate>
</asp:Repeater>
MainPage.aspx.cs
private List<Message> list;
private ESupervisionEntities db;
private MessageController message;
int id;
private System.Web.UI.WebControls.Repeater repeatComment;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["USER_NAME"] != null)
{
lblUser.Text = Session["USER_NAME"].ToString();
lblID.Text = Session["USER_ID"].ToString();
}
if (!IsPostBack)
{
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
list = message.getAllMyByID(db, id, 2);
repeater.DataSource = list;
repeater.DataBind();
}
}
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if ((item.ItemType == ListItemType.Item) ||
(item.ItemType == ListItemType.AlternatingItem))
{
repeatComment = (Repeater)item.FindControl("repeatComment");
var myLabel = e.Item.FindControl("labelID") as Label;
int num = Int32.Parse(myLabel.Text);
List<MessComment> lst = message.getAllCommentByID(db, id, num);
repeatComment.DataSource = lst;
repeatComment.DataBind();
}
}
protected void btnPost_Click(object sender, EventArgs e)
{
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
message.createMess(db, id, 2, txtMessage.Text, true);
}
protected void btnComment_Click(object sender, EventArgs e) {
var btn = (Button)sender;
var item = (RepeaterItem)btn.NamingContainer;
Button comment = (Button)item.FindControl("btnComment");
TextBox txtComment = (TextBox)item.FindControl("txtComment");
Label msgID = (Label)item.FindControl("labelID");
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
message.createComment(db, int.Parse(msgID.Text), id, 2, txtComment.Text, true);
}
Try this code...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
private void BindData()
{
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
list = message.getAllMyByID(db, id, 2);
repeater.DataSource = list;
repeater.DataBind();
}
protected void btnPost_Click(object sender, EventArgs e)
{
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
message.createMess(db, id, 2, txtMessage.Text, true);
BindData();
}
protected void btnComment_Click(object sender, EventArgs e)
{
var btn = (Button)sender;
var item = (RepeaterItem)btn.NamingContainer;
Button comment = (Button)item.FindControl("btnComment");
TextBox txtComment = (TextBox)item.FindControl("txtComment");
Label msgID = (Label)item.FindControl("labelID");
db = new ESupervisionEntities();
message = new MessageController();
id = Int32.Parse(lblID.Text);
message.createComment(db, int.Parse(msgID.Text), id, 2, txtComment.Text, true);
BindData();
}

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