dynamic data binding gridview - asp.net

my datatable formed as follows
DataTable dtFinalData = new DataTable();
//Adding columns for BR details
dtFinalData.Columns.Add("SupId", typeof(string));
dtFinalData.Columns.Add("SupName", typeof(string));
DateTime dt = DateTime.Today;
int num = DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month);
//--> adding columns for date part (1-31)
for (int i = 1; i < num + 1; i++)
{
dtFinalData.Columns.Add(i.ToString(), typeof(bool));
}
//<-- adding columns for date part (1-31)
#endregion
#region Fill dtFinalData
//--> Looping each BR from tblBrList
foreach (DataRow BrRow in dtBrList.Rows)
{
DataRow dr = dtFinalData.NewRow();
int SupId = Convert.ToInt32(BrRow[0]); //retrieve BR ID from dtBrList
String supName = BrRow[1].ToString(); //retreive Supervisor name from dtBrList
dr["SupId"] = SupId.ToString();
dr["SupName"] = supName;
for (int i = 1; i < num + 1; i++)
{
DateTime dtRunningDate = new DateTime(2013, 5, i);
//select BR_SUP_CODE,
DataRow[] drAttendance = dtAttendance.Select("BR_SUP_CODE=" + SupId + " AND SMS_DATE=#" + dtRunningDate + "#", string.Empty);
if (drAttendance.Length == 1)
{
//CheckBox chkbx = new CheckBox();
//chkbx.Checked = true;
dr[i.ToString()] = true;
}
else
{
//CheckBox chkbx = new CheckBox();
//chkbx.Checked = false;
dr[i.ToString()] = false;
}
}
dtFinalData.Rows.Add(dr);
}
//<-- Looping each BR from tblBrList
#endregion
GridView1.DataSource = dtFinalData;
GridView1.DataBind();
Now i want to add checked image in place of true and unchecked image in place of false.how to bind grid view dynamically such that in place of disable check box i want to insert two types of image?

Your DataTable part is fine and continue to add the True/False text as per the logic. Now you should handle the GridView part. So, define an event handler for the OnRowDataBound event of GridView.
In this event only, check for the Text property of the cells, and if True/False, clear the cells and add the required image.
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" ... />
And your event handler will have code as below:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Image chkImage = new Image();
chkImage.ImageUrl="~/images/Checked.png";
Image UnchkImage = new Image();
UnchkImage.ImageUrl = "~/images/UnChecked.png";
if (e.Row.RowType == DataControlRowType.DataRow)
{
// We will start from 3rd cell because the first 2 cells are
// for SupID & SupName, where we don't need to place images
for (int cellIndex = 2; cellIndex < GridView1.Columns.Count; cells++)
{
// Add Checked Image when cell text is true
if (e.Row.Cells[cellIndex].Text == "true")
{
// clear the cell and add only the image
e.Row.Cells[cellIndex].Controls.Clear();
e.Row.Cells[cellIndex].Controls.Add(chkImage);
}
// Add Unchecked Image when cell text is false
if (e.Row.Cells[cellIndex].Text == "false")
{
// clear the cell and add only the image
e.Row.Cells[cellIndex].Controls.Clear();
e.Row.Cells[cellIndex].Controls.Add(unchkImage);
}
}
}
}

Related

how to get value from dynamically created textbox in asp.net

hi i'm Cannot get value dynamically created textbox and save into database. plz help
his is code which I have created in this code text box are created but when I will input the value in the text and retrieve the value from dynamically created text box it give error
protected void btnAtt_Click(object sender, EventArgs e)
{
int DPLID = int.Parse(DPLCategory.Text);
var query = (from p in database.tbl_Attributes
where p.ProductTypeId_FK == DPLID
select new
{
p.Attribute_Id,
p.AttributeName,
p.ProductTypeId_FK,
}).ToArray();
for (int i = 0; i < query.Count(); i++)
{
Label lblatt = new Label();
lblatt.ID = query[i].AttributeName;
lblatt.Text = query[i].AttributeName + " : ";
lblatt.CssClass = "control-label";
TextBox txtatt = new TextBox();
txtatt.ID = "txtatt"+i;
txtatt.Attributes.Add("runat", "server");
txtatt.Text = String.Empty;
txtatt.CssClass = "form-control input-sm";
HtmlTextWriterTag.Br.ToString();
Place1.Controls.Add(lblatt);
HtmlTextWriterTag.Br.ToString();
Place1.Controls.Add(txtatt);
HtmlTextWriterTag.Br.ToString();
}
}
protected void lbtnSave_Click(object sender, EventArgs e)
{
int DPLID = int.Parse(DPLCategory.Text);
var query = (from p in database.tbl_Attributes
where p.ProductTypeId_FK == DPLID
select new
{
p.Attribute_Id,
p.AttributeName,
p.ProductTypeId_FK,
}).ToArray();
int LastId = database.tbl_Products.Max(p => p.ProductId);
for (int i = 0; i < query.Count(); i++)
{
database.tbl_ProductValue.Add(new Models.tbl_ProductValue()
{
ProductId_FK = LastId,
AttributeID_FK = query[i].Attribute_Id,
ProductValue = ??,
});
database.SaveChanges();
}
}
plz help me for how to get textbox?
I haven't worked with WebForms in a while but you can access the controls by their IDs like this:
ProductValue = ((TextBox)FindControl("txtatt" + i)).Text;

ASP .NET Wizard Control and View State

I have a form with 3 wizard steps, and when i click the button to dynamically add text boxes, that works fine, but when i go to the next step and i click on add to add more text boxes, it automatically adds all the text boxes from the previous steps and then continues to add if i keep click on it.
How do i prevent that from happening.
private List ControlsList
{
get
{
if (ViewState["controls"] == null)
{
ViewState["controls"] = new List();
}
return (List)ViewState["controls"];
}
}
private int NextID
{
get
{
return ControlsList.Count + 1;
}
}
protected override void LoadViewState(object savedState)
{
string section = Wizard1.ActiveStep.ID;
int sectionNum = Wizard1.ActiveStepIndex;
var control = Wizard1.ActiveStep.FindControl("Place" + sectionNum) as PlaceHolder;
base.LoadViewState(savedState);
int count = 0;
foreach (string txtID in ControlsList)
{
if (count == 0)
{
control.Controls.Add(new LiteralControl("<tr>"));
}
TextBox txt = new TextBox();
control.Controls.Add(new LiteralControl("<td>"));
txt.ID = txtID;
control.Controls.Add(txt);
control.Controls.Add(new LiteralControl("</td>"));
count = count + 1;
if (count == 3)
{
control.Controls.Add(new LiteralControl("</tr>"));
count = 0;
}
}
}
protected void AddControlButton_Click(object sender, EventArgs e)
{
string section = Wizard1.ActiveStep.ID;
int sectionNum = Wizard1.ActiveStepIndex;
var control = Wizard1.ActiveStep.FindControl("Place" + sectionNum) as PlaceHolder;
TextBox txt1 = new TextBox();
TextBox txt2 = new TextBox();
TextBox txt3 = new TextBox();
txt1.ID = section.ToString() + "Size" + NextID.ToString();
control.Controls.Add(new LiteralControl("<td>"));
control.Controls.Add(txt1);
control.Controls.Add(new LiteralControl("</td>"));
ControlsList.Add(txt1.ID);
txt2.ID = section.ToString() + "Description" + NextID.ToString();
control.Controls.Add(new LiteralControl("<td>"));
control.Controls.Add(txt2);
control.Controls.Add(new LiteralControl("</td>"));
ControlsList.Add(txt2.ID);
txt3.ID = section.ToString() + "Quantity" + NextID.ToString();
control.Controls.Add(new LiteralControl("<td>"));
control.Controls.Add(txt3);
control.Controls.Add(new LiteralControl("</td></tr>"));
ControlsList.Add(txt3.ID);
}
You are storing all of the dynamic textboxes in ViewState and then the ControlsList property getter is returning the whole list when it is building the textboxes.
My recommendation is to use Session cache instead of ViewState, because it will allow you to differentiate the textbox controls from each of the wizard steps, like this:
Session["WizardStep1"] = listOfTextBoxesFromStep1;
Session["WizardStep2"] = listOfTextBoxesFromStep2;
Session["WizardStep3"] = listOfTextBoxesFromStep3;

Deleting records from table

In the above photo I have a table containing a list of users that are add dynamically in the table.
I want when I click on the red-cross image button the corresponding user to be deleted from the database.
Here is the code that fills the table:
/****** Filling the originators table ********/
string[] oa1 = originator;
for (int i = 0; i < oa1.Length; i++)
{
TableRow row = new TableRow();
users_table.Rows.Add(row);
for (int colCount = 0; colCount < 4; colCount++)
{
TableCell cell = new TableCell();
row.Cells.Add(cell);
if (colCount == 0)
{
cell.Controls.Add(new LiteralControl(oa1[i]));
}
else if (colCount == 1)
{
cell.Controls.Add(new LiteralControl("|"));
}
else if (colCount == 2)
{
LLKB userInfo = new LLKB();
cell.Controls.Add(new LiteralControl(userInfo.InfoGetter(oa1[i].Trim(), "name")));
}
else if (colCount == 3)
{
ImageButton btn = new ImageButton();
btn.ImageUrl = "img/DeleteRed.png";
btn.ID = oa1[i] + "_" + i;
btn.Click += new ImageClickEventHandler(delete_originator);
cell.Controls.Add(btn);
}
}
}
and here is the method that show do the deletion:
public void delete_originator(object sender, ImageClickEventArgs e)
{
//some code here
}
So, what do you suggest I write in the deletion method??
or if you have another idea...
you should empty table and recreate the table and get username thorugh spliting imagebutton ID
by '_',So in loop when that username come you add continue statement.
some thing like that in Delete event :
string Username=((imagebutton)sender).ID.toString().tosplit('_')[0];

Accessing the TextBox Contents in Dynamically Created GridView

i created gridview dynamically,
which consists of Textboxes and buttonfield, on row command event of the gridview i want to access the content of textbox.
i am not able to access the textbox
here is my code
protected void FillGridListTollCollection()
{
TollCollectionBLLC tollcollectionBLLC = new TollCollectionBLLC();
dataTable = tollcollectionBLLC.GetTollCollectionDetailsBLLC(187, 1, 1, "10/10/2011");
//put the gridview into the placeholder to get the values of textboxes in gridview
PlaceHolder1.Controls.Add(GridListTollColletion);
foreach (DataColumn col in dataTable.Columns)
{
if (col.ToString() == "TollCollID")
{
BoundField bField = new BoundField();
bField.HeaderText = "TollCollID";
bField.DataField = "TollCollID";
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "TollAmtApplicable")
{
BoundField bField = new BoundField();
bField.HeaderText = "TollAmtApplicable";
bField.DataField = "TollAmtApplicable";
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "TollCollDesc")
{
BoundField bField = new BoundField();
bField.HeaderText = "Transaction Types";
bField.DataField = "TollCollDesc";
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "Total")
{
BoundField bField = new BoundField();
bField.HeaderText = "Total";
bField.DataField = "Total";
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString().Contains("Rate"))
{
BoundField bField = new BoundField();
bField.HeaderText = col.ToString();
bField.DataField = col.ToString();
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
//Declare the bound field and allocate memory for the bound field.
TemplateField tfield = new TemplateField();
//Initalize the DataField value.
tfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);
tfield.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
tfield.HeaderStyle.VerticalAlign = VerticalAlign.Middle;
tfield.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
tfield.ItemStyle.VerticalAlign = VerticalAlign.Middle;
//Initialize the HeaderText field value.
tfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);
//Add the newly created bound field to the GridView.
GridListTollColletion.Columns.Add(tfield);
}
protected void GridListTollColletion_RowCommand(object sender, GridViewCommandEventArgs e)
{
int tempCarCount = 0;
// here i am getting exception
int.TryParse( ( (TextBox)GridListTollColletion.Rows[Convert.ToInt32(e.CommandArgument)].Cells[Convert.ToInt32(e.CommandArgument)].Controls[3]).Text , out tempCarCount);
}
public class GridViewTemplate : ITemplate
{
//A variable to hold the type of ListItemType.
ListItemType _templateType;
//A variable to hold the column name.
string _columnName;
//Constructor where we define the template type and column name.
public GridViewTemplate(ListItemType type, string colname)
{
//Stores the template type.
_templateType = type;
//Stores the column name.
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
//Creates a new label control and add it to the container.
Label lbl = new Label(); //Allocates the new label object.
lbl.Text = _columnName; //Assigns the name of the column in the lable.
container.Controls.Add(lbl); //Adds the newly created label control to the container.
break;
case ListItemType.Item:
//Creates a new text box control and add it to the container.
TextBox tb1 = new TextBox(); //Allocates the new text box object.
tb1.Width = 60;
tb1.Height = 22;
tb1.MaxLength = 50;
tb1.ID = "v";
//Creates a column with size 4.
tb1.DataBinding += new EventHandler(tb1_DataBinding); //Attaches the data binding event.
tb1.Columns = 7;
container.Controls.Add(tb1);
//Adds the newly created textbox to the container.
break;
case ListItemType.EditItem:
//As, I am not using any EditItem, I didnot added any code here.
break;
case ListItemType.Footer:
CheckBox chkColumn = new CheckBox();
chkColumn.ID = "Chk" + _columnName;
container.Controls.Add(chkColumn);
break;
}
}
public IOrderedDictionary ExtractValues(Control container)
{
OrderedDictionary dict = new OrderedDictionary();
if (_templateType == ListItemType.Item)
{ string value = ((TextBox)container.FindControl("tb1" + _columnName)).Text;
dict.Add(_columnName, value); }
return dict;
}
void tb1_DataBinding(object sender, EventArgs e)
{
TextBox txtdata = (TextBox)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
txtdata.Text = dataValue.ToString();
}
}
public GridViewTemplate()
{
//
// TODO: Add constructor logic here
//
}
}
The template is applied statically. So, you wont be able to access the control as you are trying to do.
Try using -
var textbox = GridListTollColletion.FindControl(<yourtextbox>);
Is it not convenient if you bind these added controls on GridView.RowDataBound event.
Check this BindData to ITemplate for GridView in code behind
If you are following this MSDN Article How To: Create ASP.NET Web Server Control Templates Dynamically to take idea about this then check this code snippet.
static void Item_DataBinding(object sender, System.EventArgs e)
{
PlaceHolder ph = (PlaceHolder)sender;
RepeaterItem ri = (RepeaterItem)ph.NamingContainer;
Int32 item1Value = (Int32)DataBinder.Eval(ri.DataItem, "CategoryID");
String item2Value = (String)DataBinder.Eval(ri.DataItem, "CategoryName");
((Label)ph.FindControl("item1")).Text = item1Value.ToString();
((Label)ph.FindControl("item2")).Text = item2Value;
}
It have Item_DataBinding a static method. you are setting up this stuff statically, so check this article to improve your code.
In Edit Template i suggest you to use RowBound Event to handle for these template controls.. there you can easily access them.

Bind a multi-dimensional ArrayList to a Gridview

I have a DataGrid of seats available, each with a checkbox to be able to reserve the seat. In the button click event, if the CheckBox is clicked, I am adding the contents of the row to an ArrayList, then adding the ArrayList to a session before redirecting to the confirmation page:
protected void Reserve_Click(object sender, EventArgs e)
{
{
ArrayList seatingArreaList = new ArrayList();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
Guid SeatId = (Guid)GridView1.DataKeys[i][0];
CheckBox cbReserve = (CheckBox)GridView1.Rows[i].FindControl("cbReserve");
Label lblSection = (Label)GridView1.Rows[i].FindControl("lblSection");
Label lblRow = (Label)GridView1.Rows[i].FindControl("lblRow");
Label lblPrice = (Label)GridView1.Rows[i].FindControl("lblPrice");
if (cbReserve.Checked)
{
string tempRowInfo = lblSection.Text + "|" + lblRow.Text + "|" + lblPrice.Text;
seatingArreaList.Add(tempRowInfo);
}
}
// Add the selected seats to a session
Session["Seating"] = seatingArreaList;
}
Response.Redirect("Confirm.aspx?concertId=" + Request.QueryString["concertId"]);
}
On the confirmation page, Id like to split this array up and bind it to another gridview in their individual columns.
On the confirmation page, a session exists that has three columns separated with a pipe, I am struggling to split this up and bind it to a confirmation grid.
Please help!
This would probably be easier to just create a DataTable, then add it to the session variable. Once redirected to the confirmation page just bind GridView to the DataTable pulled from the session variable.
protected void Reserve_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Section");
dt.Columns.Add("Row");
dt.Columns.Add("Price");
{
ArrayList seatingArreaList = new ArrayList();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
Guid SeatId = (Guid)GridView1.DataKeys[i][0];
CheckBox cbReserve = (CheckBox)GridView1.Rows[i].FindControl("cbReserve");
Label lblSection = (Label)GridView1.Rows[i].FindControl("lblSection");
Label lblRow = (Label)GridView1.Rows[i].FindControl("lblRow");
Label lblPrice = (Label)GridView1.Rows[i].FindControl("lblPrice");
if (cbReserve.Checked)
{
DataRow dr = dt.NewRow();
dr["Section"] = lblSection.Text;
dr["Row"] = lblRow.Text;
dr["Price"] = lblPrice.Text;
dt.Rows.Add(dr);
}
}
// Add the selected seats to a session
Session["Seating"] = dt;
}
Response.Redirect("Confirm.aspx?concertId=" + Request.QueryString["concertId"]);
}
var q = from dto in seatingArreaList
let z = dto.Split("|".ToCharArray())
select z;
and then just bing q to the grid.

Resources