Unable to Find Control in RowEditing event for TemplateFields in GridView - c#

I am adding columns to gridview from codebehind.
For boundfields, i am able to find control and textbox value while updating the row.
But for template fields, i am not able to get controls to the code behind, so i am unable to get the textbox value.
Can please suggest how to get textbox value in codebehind for template fields
My Code
protected void gvbind()
{
conn.Open();
string Query = "SELECT * FROM testactiondatabase_db.actions";
MySqlCommand MyCommand2 = new MySqlCommand(Query, conn);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dt = new DataTable();
MyAdapter.Fill(dt);
TaskGridView.Columns.Clear();
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Columns[i].ColumnName.ToString().ToUpper().Contains("DATE"))
{
TemplateField bfield = new TemplateField();
bfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, dt.Columns[i].ColumnName.ToString());
bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, dt.Columns[i].ColumnName.ToString());
bfield.EditItemTemplate = new GridViewTemplate(ListItemType.EditItem, dt.Columns[i].ColumnName.ToString());
TaskGridView.Columns.Add(bfield);
}
else
{
BoundField boundfield = new BoundField();
boundfield.DataField = dt.Columns[i].ColumnName.ToString();
boundfield.HeaderText = dt.Columns[i].ColumnName.ToString();
TaskGridView.Columns.Add(boundfield);
}
}
TaskGridView.DataSource = dt;
TaskGridView.DataBind();
TaskGridView.Width = 600;
TaskGridView.HeaderStyle.CssClass = "header";
TaskGridView.RowStyle.CssClass = "rowstyle";
conn.Close();
}
public class GridViewTemplate : ITemplate
{
ListItemType _templateType;
string _columnName;
public GridViewTemplate(ListItemType type, string colname)
{
_templateType = type;
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
Label lbl = new Label();
lbl.Text = _columnName;
container.Controls.Add(lbl);
break;
case ListItemType.Item:
Label lb1 = new Label();
lb1.DataBinding += new EventHandler(lb1_DataBinding);
container.Controls.Add(lb1);
break;
case ListItemType.EditItem:
TextBox tb1 = new TextBox();
tb1.ID = _columnName;
tb1.DataBinding += new EventHandler(tb1_DataBinding);
tb1.Attributes.Add("class", "myDatePickerClass");
container.Controls.Add(tb1);
break;
case ListItemType.Footer:
CheckBox chkColumn = new CheckBox();
chkColumn.ID = "Chk" + _columnName;
container.Controls.Add(chkColumn);
break;
}
}
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 = Convert.ToDateTime(dataValue.ToString()).ToString("dd/MM/yyyy");
}
}
void lb1_DataBinding(object sender, EventArgs e)
{
Label txtdata = (Label)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
txtdata.Text = Convert.ToDateTime(dataValue.ToString()).ToString("dd/MM/yyyy");
}
}
}
I am using the following code for reading the template field textbox value while updating the row but the controls are 0 for the cell.
GridViewRow row = (GridViewRow)TaskGridView.Rows[e.RowIndex];
TextBox textnew = (TextBox)row.Cells[j].Controls[0];

Try using FindControl.
TextBox textnew = TaskGridView.Rows[e.RowIndex].FindControl(_columnName) as TextBox;
But if I use your snippet like this, with setting an EditIndex manually, it also works... The value of te TextBox is Cell 1 is changed.
TaskGridView.EditIndex = 1;
TaskGridView.DataSource = dt;
TaskGridView.DataBind();
TaskGridView.Width = 600;
TaskGridView.HeaderStyle.CssClass = "header";
TaskGridView.RowStyle.CssClass = "rowstyle";
GridViewRow row = (GridViewRow)TaskGridView.Rows[TaskGridView.EditIndex];
TextBox textnew = (TextBox)row.Cells[1].Controls[0];
textnew.Text = "test";

Related

My Cart Label Value is not increasing in masterpage?

MasterPage Code:
public Label OnlbCartCountMasterPage {
get { return this.chartlabel; }
}
Index.aspx Code
String cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
string cartQuantity;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadList();
}
if (Session["addtocart"] != null)
{
DataTable dt = new DataTable();
cartQuantity = Convert.ToString(dt.Rows.Count);
}
else
{
cartQuantity = "0";
}
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
Add2cart Method:
private void add2cart(int id,string lblname,int lblPrice, int lbltotal, int quantitylist, string image)
{
if (Session["addtocart"] != null)
{
DataTable dt = (DataTable)Session["addtocart"];
var dataRow = dt.AsEnumerable().Where(x => x.Field<int>("ID") == id);
if (dataRow.Count() == 0)
{
//lblErrorMessage.Text = "";
DataRow dr = dt.NewRow();
dr["ID"] = id;
dr["Item"] = lblname;
dr["Price"] = lblPrice;
dr["quantity"] = quantitylist;
dr["total"] = lbltotal;
dr["image"] = image;
dt.Rows.Add(dr);
Session["addtocart"] = dt;
cartQuantity= dt.Rows.Count.ToString();
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
else
{
//lblErrorMessage.Text = "Item Already Added!";
}
}
else
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Item", typeof(string));
dt.Columns.Add("Price", typeof(int));
dt.Columns.Add("quantity", typeof(int));
dt.Columns.Add("total", typeof(int));
dt.Columns.Add("image", typeof(string));
DataRow dr = dt.NewRow();
dr["ID"] = id;
dr["Item"] = lblname;
dr["Price"] = lblPrice;
dr["quantity"] = quantitylist;
dr["total"] = lbltotal;
dr["image"] = image;
dt.Rows.Add(dr);
Session["addtocart"] = dt;
cartQuantity=Convert.ToString(dt.Rows.Count);
}
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
Button Code
protected void btnAddtoCart_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ListViewItem item = (ListViewItem)btn.NamingContainer;
HiddenField hfid = item.FindControl("hfId") as HiddenField;
Label lblitem= item.FindControl("item") as Label;
Label lblPrice = item.FindControl("lblPrice") as Label;
DropDownList lblQuantity = item.FindControl("qtydrpdwn") as DropDownList;
Label lblTotal = item.FindControl("Total") as Label;
HiddenField hfimg = item.FindControl("imgpath") as HiddenField;
add2cart(Convert.ToInt32(hfid.Value),lblitem.Text, Convert.ToInt32(lblPrice.Text), Convert.ToInt32(lblTotal.Text), Convert.ToInt32(lblQuantity.Text),hfimg.Value);
btn.Enabled = false;
//Response.Redirect("index.aspx");
}
The problem is occuring in pageload i think? because session is not recognizing the value coming from add2cart method. it is showing the value in the session of add to cart but not in page load. i cant finding out the problem in the code?
And when i click the button to add to cart. the value remains same 0 not increasing at all?
Try this. I outsourced the update routine in a seperate method which is called each time the button is pressed.
String cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
string cartQuantity;
// this will be executed when the page is loaded at the beginning or when refreshed
protected void Page_Load(object sender, EventArgs e)
{
// I don't know what this does, if you also need it for the update
// then put it into the updateQuantity method
if (!IsPostBack)
{
LoadList();
}
// update quantity
updateQuantity();
}
// method to update the quantity
private void updateQuantity()
{
if (Session["addtocart"] != null)
{
DataTable dt = new DataTable();
cartQuantity = Convert.ToString(dt.Rows.Count);
}
else
{
cartQuantity = "0";
}
Master.OnlbCartCountMasterPage.Text = cartQuantity;
}
protected void btnAddtoCart_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ListViewItem item = (ListViewItem)btn.NamingContainer;
HiddenField hfid = item.FindControl("hfId") as HiddenField;
Label lblitem= item.FindControl("item") as Label;
Label lblPrice = item.FindControl("lblPrice") as Label;
DropDownList lblQuantity = item.FindControl("qtydrpdwn") as DropDownList;
Label lblTotal = item.FindControl("Total") as Label;
HiddenField hfimg = item.FindControl("imgpath") as HiddenField;
add2cart(Convert.ToInt32(hfid.Value),lblitem.Text, Convert.ToInt32(lblPrice.Text), Convert.ToInt32(lblTotal.Text), Convert.ToInt32(lblQuantity.Text),hfimg.Value);
btn.Enabled = false;
//call update method
updateQuantity();
}

the selectedindex and selectedvalue attributes are mutually exclusive exception?

protected void ddlbranchdate_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DataTable dtgetvalues = new DataTable();
//objRetailPL.date = Convert.ToDateTime(hdndate.Value);
objRetailPL.branchdate = ddlbranchdate.SelectedItem.ToString();
dtgetvalues = objRetailBAL.getbradisdate(objRetailPL);
foreach(GridViewRow row in gvMeatDispatch.Rows)
{
DataTable dtpr = new DataTable();
DropDownList ddl1 = (DropDownList)row.FindControl("ddlpartyname");
objRetailPL.branch = dtgetvalues.Rows[0]["branch"].ToString();
dtpr = objRetailBAL.getbran(objRetailPL);
ddl1.DataSource = dtpr;
ddl1.DataTextField = "partyname";
ddl1.DataValueField = "sno";
ddl1.DataBind();
ddl1.Items.Add(new ListItem("--Select--", "0"));
ddl1.SelectedIndex = ddl1.Items.Count - 1;
}
}
}
why i am getting this exception?..
i am using Dynamic Gridview and adding Rows Dynamically with the help of Button Control..
Outside i am declare another dropdown list ..if user selected some value from this Dropdownlist
then automatically bind the values to Dynamic Gridview ,Dropdown list values..
This is my Setprevious Data in Dynamic control Method..Here i called Dropdownlist selectedindexchanged event ..like..
private void SetPreviousData()
{
try
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList ddlpname = (DropDownList)gvMeatDispatch.Rows[rowIndex].Cells[1].FindControl("ddlpartyname");
DropDownList ddlbt = (DropDownList)gvMeatDispatch.Rows[rowIndex].Cells[2].FindControl("ddlbirdtype");
TextBox txttotwt = (TextBox)gvMeatDispatch.Rows[rowIndex].Cells[3].FindControl("txttotwt");
TextBox txttransbirds1 = (TextBox)gvMeatDispatch.Rows[rowIndex].Cells[4].FindControl("txtrateforkg");
TextBox txtmort1 = (TextBox)gvMeatDispatch.Rows[rowIndex].Cells[5].FindControl("txtdcno");
// Dropdownlist selectedIndex Changed event
ddlbranchdate_SelectedIndexChanged(null, null);
ddlpname.SelectedValue = dt.Rows[i]["Col1"].ToString();
ddlbt.SelectedValue = dt.Rows[i]["Col2"].ToString();
txttotwt.Text = dt.Rows[i]["col3"].ToString();
txttransbirds1.Text = dt.Rows[i]["Col4"].ToString();
txtmort1.Text = dt.Rows[i]["Col5"].ToString();
rowIndex++;
}
}
}
}

Apply Column Filtering in Gridview in asp.net

I have a gridview which is populated at runtime with a table with unknow number of columns which are not known before hand.
I want to apply column filtering on all columns with Drop Down List.
How can I achieve it. Using Jquery, Linq or simple C sharp Coding.
public partial class DetailView : System.Web.UI.Page
{
public static int y = 0;
public static String colName = "";
public static Boolean flag = false;
static String folder = "";
static public MySqlConnection conn = null;
static public DropDownList dp = null;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string strcon = ConfigurationManager.ConnectionStrings["abc"].ConnectionString;
conn = new MySqlConnection(strcon);
conn.Open();
Response.Write(Session["cols"].ToString());
Response.Write(Session["id"].ToString());
// Response.Write("qw");
folder = Session["folderName"].ToString();
colName = Session["cols"].ToString();
GridBind(folder, colName, flag);
}
protected void Page_Load(object sender, EventArgs e)
{
}
public void GridBind(String folder, String colName, Boolean val)
{
GridView1.DataSource = null;
GridView1.DataBind();
GridView1.Columns.Clear();
y = 0;
MySqlDataAdapter da;
if (val == false)
{
da = new MySqlDataAdapter("select * from " + folder + "", conn);
}
else
{
da = new MySqlDataAdapter("select * from " + folder + " where abc= '" + colName + "'", conn);
}
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataColumn coloumn in dt.Columns)
{
if (!coloumn.ColumnName.Equals("emp"))
{
var linkF = new TemplateField();
linkF.HeaderText = coloumn.ColumnName;
linkF.HeaderTemplate = new LinkColumn(ListItemType.Header, coloumn.ColumnName,folder);
linkF.ItemTemplate = new LinkColumn(ListItemType.Item, coloumn.ColumnName,folder);
GridView1.Columns.Add(linkF);
}
else if (coloumn.ColumnName.Equals("emp"))
{
//Response.Write("Came");
BoundField bfield = new BoundField();
////Initalize the DataField value.
bfield.DataField = coloumn.ColumnName;
////Initialize the HeaderText field value.
bfield.HeaderText = coloumn.ColumnName;
GridView1.Columns.Add(bfield);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
class LinkColumn : DetailView, ITemplate
{
int id;
ListItemType _item;
String colN = null;
String fold;
public LinkColumn(ListItemType item, String colNa, String f)
{
_item = item;
colN = colNa;
fold = f;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_item)
{
case ListItemType.Header:
DetailView.dp = new DropDownList();
Label lb = new Label();
MySqlCommand cm = new MySqlCommand("select distinct " + colN + " from " + fold + "", conn);
MySqlDataAdapter ad = new MySqlDataAdapter();
DataTable d = new DataTable();
ad.SelectCommand = cm;
ad.Fill(d);
DetailView.dp.DataTextField = colN;
DetailView.dp.DataValueField = colN;
DetailView.dp.DataSource = d;
DetailView.dp.DataBind();
lb.Text = colN.ToUpperInvariant();
dp.AutoPostBack = true;
dp.EnableViewState = true;
// DetailView.dp.ID = y.ToString();
y++;
container.Controls.Add(lb);
container.Controls.Add(DetailView.dp);
// DetailView.dp.ID = DetailView.y.ToString();
// Response.Write(_Default.dp.ID);
DetailView.dp.SelectedIndexChanged += new EventHandler(dp_Selected);
break;
case ListItemType.Item:
TextBox tb1 = new TextBox();
tb1.Enabled = false;
tb1.DataBinding += new EventHandler(tb1_Data);
tb1.Columns = 30;
container.Controls.Add(tb1);
break;
}
}
void tb1_Data(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow cont = (GridViewRow)txt.NamingContainer;
object dataV = DataBinder.Eval(cont.DataItem, colN);
if (dataV != DBNull.Value)
{
txt.Text = dataV.ToString();
}
}
void dp_Selected(object sender, EventArgs e)
{
DataTable a = new DataTable();
DropDownList list = (DropDownList)sender;
String name = list.SelectedValue;
// String ID = list.ID.ToString();
// Session["id"] = ID;
Session["cols"] = name;
DetailView.colName = Session["cols"].ToString();
DetailView.flag = true;
// Response.Write(DetailView.colName);
GridBind(fold, DetailView.colName, true);
}
}
}
When i am calling GridBind function from event handler it is giving Null pointer Excpetion at GridView1.DataSource = null;
My GridView1 is present in DetailView.aspx
}
Any help be highly appreciated
Thanks

cannot bind data to gridview combobox in datagridview at editing mode

The following is my code for row editing event.
protected void branchgrid_RowEditing(object sender, GridViewEditEventArgs e)
{
if (TextBox1.Text == "")
{
workingdaygrid.EditIndex = e.NewEditIndex;
bindworkingday();
GridViewRow row = workingdaygrid.Rows[e.NewEditIndex];
DropDownList dl = row.FindControl("Workingdaytype") as DropDownList;
DataTable worktype = inter.bindworkdaytype();
dl.DataSource = worktype;
dl.DataTextField = "Workingday_type";
dl.DataValueField = "Time_id";
dl.DataBind();
}
else
{
string datetime = TextBox1.Text;
comp.DATETIME = Convert.ToDateTime(datetime);
DataTable result = inter.searchworkday(comp);
workingdaygrid.DataSource = result;
workingdaygrid.DataBind();
workingdaygrid.EditIndex = e.NewEditIndex;
GridViewRow row = workingdaygrid.Rows[e.NewEditIndex];
DropDownList dl = row.FindControl("Workingdaytype") as DropDownList;
DataTable worktype = inter.bindworkdaytype();
//string datetime = TextBox1.Text;
dl.DataSource = worktype;
dl.DataTextField = "Workingday_type";
dl.DataValueField = "Time_id";
dl.DataBind();
}
after filtration using search button, I am trying editing the particular row(data) but i cannot get the gridview combobox value. it is blank. but in the full databind(first if condition) combobox value is binded.
my seach button code is
string datetime = TextBox1.Text;
comp.DATETIME = Convert.ToDateTime(datetime);
DataTable result = inter.searchworkday(comp);
workingdaygrid.DataSource = result;
workingdaygrid.DataBind();

add button in a gridview dynamically populate: event click not fire

I work several time on this functions but also not working at all.
I populate a gridview by code and I add a button that open a detail of row on click.
I try to add button while populate datatable but not work.
After I try to add button on row_databound method; the button it's rendering but not fire event click.
As follow a semplify code.
I hope that you are able to help me to solve this problem.
Thank's in advance and regards.
P
protected void btnSearch_Click(object sender, EventArgs e)
{
string sSearchQuery = "(" + TextBox1.Text + ")";
loadDynamicGrid(sSearchQuery);
}
private void loadDynamicGrid(string sSearchQuery)
{
//search
.....
var oHitColl = searcher.Search(oParser.Parse(sSearchQuery));
//istance of DataTable
gvResult.Columns.Clear();
gvResult.DataSource = null;
DataTable dt = new DataTable();
DataColumn dcol = new DataColumn("Id", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Table", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Summary", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Link", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Button", typeof(Button));
dt.Columns.Add(dcol);
//Populate la datatable
for (int i = 0; i < oHitColl.Length(); i++)
{
Document oDoc = oHitColl.Doc(i);
DataRow drow = dt.NewRow();
drow["Table"] = oDoc.Get("Table");
drow["Summary"] = oDoc.Get("Summary");
drow["Id"] = oDoc.Get("Id");
string url = ....".aspx";
drow["Link"] = linkText;
//Button btn = CreateButton("dinamicBtn" + i.ToString(), "dinamicBtn" + i.ToString());
//drow["Button"] = btn;
dt.Rows.Add(drow);
}
// add columus in GridView
foreach (DataColumn col in dt.Columns)
{
//Dichiarare i campi bindati e allocare la memoria che serve
BoundField bfield = new BoundField();
bfield.DataField = col.ColumnName;
bfield.HeaderText = col.ColumnName;
gvResult.Columns.Add(bfield);
}
gvResult.DataSource = dt;
gvResult.DataBind();
searcher.Close();
}
protected void gvResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = new Button();
btn = CreateButton("btnOpen_"+ e.Row.RowIndex.ToString(), "Open");
btn.DataBinding +=new EventHandler(btn_DataBinding);
e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(btn);
}
}
private Button CreateButton(string id, string name)
{
Button b = new Button();
b.Text = name;
b.ID = id;
b.Click += new EventHandler(Dynamic_Method);
b.DataBinding += new EventHandler(btn_DataBinding);
return b;
}
private void btn_DataBinding(object sender, EventArgs e)
{
object bound_value_obj = null;
Control ctrl = (Control)sender;
IDataItemContainer data_item_container = (IDataItemContainer)ctrl.NamingContainer;
bound_value_obj = DataBinder.Eval(data_item_container.DataItem,"gvResult.Rows.Count.ToString()");
}
protected void Dynamic_Method(object sender, EventArgs e)
{
Response.Write("You have clicked at: "+DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
}
Any control that you create dynamically need to be re-added at every postback, the events need to be hooked at every postback, etc. In addition to that, you should do this in the OnInit method.

Categories

Resources