add boundField to gridview in codebehind file C# - asp.net

I want to create new gridview in codebehind file asp.net C#.
Exactly I want to add such boundfield to the gridview by c# code:
<asp:BoundField DataField="p_type" HeaderText="type" ItemStyle-Width="70px">
<ItemStyle Width="70px"></ItemStyle>
</asp:BoundField>
I crated new gridview with following code:
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.CellPadding = 4;
GridView1.GridLines= GridLines.None;
GridView1.AutoGenerateColumns = false;
And I want to add new boundField to this gridview.
How to make that with c# code?

this article explain you how implement in c# code a gridview :
http://www.codeproject.com/Articles/13461/how-to-create-columns-dynamically-in-a-grid-view
here a sample code to create it:
public partial class _Default : System.Web.UI.Page
{
#region constants
const string NAME = "NAME";
const string ID = "ID";
#endregion
protected void Page_Load(object sender, EventArgs e)
{
loadDynamicGrid();
}
private void loadDynamicGrid()
{
#region Code for preparing the DataTable
//Create an instance of DataTable
DataTable dt = new DataTable();
//Create an ID column for adding to the Datatable
DataColumn dcol = new DataColumn(ID ,typeof(System.Int32));
dcol.AutoIncrement = true;
dt.Columns.Add(dcol);
//Create an ID column for adding to the Datatable
dcol = new DataColumn(NAME, typeof(System.String));
dt.Columns.Add(dcol);
//Now add data for dynamic columns
//As the first column is auto-increment, we do not have to add any thing.
//Let's add some data to the second column.
for (int nIndex = 0; nIndex < 10; nIndex++)
{
//Create a new row
DataRow drow = dt.NewRow();
//Initialize the row data.
drow[NAME] = "Row-" + Convert.ToString((nIndex + 1));
//Add the row to the datatable.
dt.Rows.Add(drow);
}
#endregion
//Iterate through the columns of the datatable to set the data bound field dynamically.
foreach (DataColumn col in dt.Columns)
{
//Declare the bound field and allocate memory for the bound field.
BoundField bfield = new BoundField();
//Initalize the DataField value.
bfield.DataField = col.ColumnName;
//Initialize the HeaderText field value.
bfield.HeaderText = col.ColumnName;
//Add the newly created bound field to the GridView.
GrdDynamic.Columns.Add(bfield);
}
//Initialize the DataSource
GrdDynamic.DataSource = dt;
//Bind the datatable with the GridView.
GrdDynamic.DataBind();
}
}

Related

gridview data is null in when passing gridview to another method

I bind the gridview in the following event:(subjectdropdown_SelectedIndexChanged)
I send the gridview in the following event as a parameter to another method:Button1_click event.
protected void subjectdropdown_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable getmarkfdb = inter.getmarksfromdatabaseothers(comp);
if (getmarkfdb.Rows.Count > 0)
{
TemplateField lable1 = new TemplateField();
lable1.ShowHeader = true;
lable1.HeaderText = "AdmissionNumber";
lable1.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "AdmissionNumber", "AdmissionNumber", "Label");
studmarkgrid.Columns.Add(lable1);
TemplateField label2 = new TemplateField();
label2.ShowHeader = true;
label2.HeaderText = "RollNumber";
label2.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "RollNumber", "RollNumber", "Label");
studmarkgrid.Columns.Add(label2);
TemplateField label3 = new TemplateField();
label3.ShowHeader = true;
label3.HeaderText = "Name";
label3.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "Name", "Name", "Label");
studmarkgrid.Columns.Add(label3);
TemplateField extmep = new TemplateField();
extmep.ShowHeader = true;
extmep.HeaderText = "ExternalMark";
extmep.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "ExternalMark", "ExternalMark", "TextBox");
studmarkgrid.Columns.Add(extmep);
studmarkgrid.DataSource = getmarkfdb;
studmarkgrid.DataBind();
}
}
In the TextBoxTemplate column of the gridview I fill the Mark for student and in the following event i send the gridview to insertstumark method for read data from gridview and save into database. but in the insertstumark method gridview rows data are null.
protected void Button1_Click(object sender, EventArgs e)
{
comp.ACADAMICYEAR = acyeardropdown.SelectedItem.Text;
comp.MEDIUM = mediumdropdown.SelectedItem.Text;
string clas = classdropdown.SelectedItem.Text;
string[] cs = clas.Split('-');
comp.CLASSNAME = cs[0].ToString();
comp.SECTIONNAME =Convert.ToChar(cs[1].Trim().ToString());
comp.EXAMNAMES = examnamedropdown.SelectedItem.Text;
comp.SUBJECTID = subjectdropdown.SelectedValue.ToString();
// studmarkgrid.DataBind();
// System.Web.UI.WebControls.GridView grid = studmarkgrid;
// System.Web.UI.WebControls.GridView grid = ViewState["stdmarkgrid"] as System.Web.UI.WebControls.GridView;
DataTable studtable = null;
// System.Web.UI.WebControls.GridView grid = (System.Web.UI.WebControls.GridView)ViewState["stdmarkgrid"];
bool studm = inter.inserstumark(comp,stumarkgrid);
}
What is the problem. I tried to stored the gridview in viewstate. but in the following line it through the error. How to solve this problem?
System.Web.UI.WebControls.GridView grid = ViewState["stdmarkgrid"] as System.Web.UI.WebControls.GridView;
A lot of times, if the data is bound to the GridView too late in the Page Lifecycle, the GridView is rendered, and the data forgotten, so at the next PostBack, you won't have access to the GridView's underlying data source.
That looks like what's happening here. Just save the result of getmarksfromdatabaseothers to ViewState so you can access it again as necessary.

how to get gridview all rows data when using paging

I have a gridview with paging (page size 10), which contains Course details. when i am saving gridview data into database it save only 10 record (according to page).
is there any to get all gridview all rows.
e.g. if my gridview contains 25 rows with paging and when i save data into database then all 25 rows data insert into database?
please help...
Here is my code
DataTable dt = new DataTable();
dt.Columns.Add("row_index");
dt.Columns.Add("edited_value");
IList<int?> SeqNos = new List<int?>();
foreach (GridViewRow gvr in gvViolationCodes.Rows)
{
TextBox tb = (TextBox)gvr.FindControl("txtSeqNo");
Label lblSysid = (Label)gvr.FindControl("lblSysID");
HiddenField hf = (HiddenField)gvr.FindControl("HiddenField1");
if (tb.Text != hf.Value)
{
DataRow dr = dt.NewRow();
SeqNos.Add(Convert.ToInt32(tb.Text));
dr["row_index"] = lblSysid.Text;
dr["edited_value"] = tb.Text;
dt.Rows.Add(dr);
}
}
You need to save the data in temporary storage in PageIndexChanging event of GrIdView. On final save send the datatable to Sql Server Procedure or loop through the datatable and save it in database. Follow the steps:
protected void grdView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
fnStoreGridData();
}
private void fnStoreGridData()
{
DataTable TempDataTable = new DataTable();
if(Session["Data"]!=null){
TempDataTable = Session["Data"] as DataTable;
}
else{
TempDataTable.Columns.Add("exCourse", typeof(string)) ;
TempDataTable.Columns.Add("exUniversityCourse", typeof(string)) ;
}
foreach (GridViewRow row in gvExportCourse.Rows)
{
Label exCourse = (Label)row.FindControl("gvlblCourseName");
Label exUniversityCourse = (Label)row.FindControl("gvlblUniversityCourseName");
if (exCourse != null)
{
if (!string.IsNullOrEmpty(exCourse.Text))
{
TempDataTable.Rows.Add(exCourse.Text, exUniversityCourse.Text);
//TempDataTable is your datatable object. Make sure that datatable contains these columns
}
}
}
}
In Final Save:
protected void button_Click(object s, EventArg e)
{
fnStoreGridData(); //Here this will bind the data of current page
DataTable TempDataTable = new DataTable();
if(Session["Data"]!=null){
TempDataTable = Session["Data"] as DataTable;
}
//Now loop through datatable and store the values
foreach(DataRow in TempDataTable.Rows)
{
CourseInformation course = new CourseInformation();
course.AddCourseMaster(dr["exCourse"].ToString(), dr["exUniversityCourse"].ToString());
}
label1.Text = "Course saved successfully.";
}

How to store ButtonField in a datarow where the column is set for ButtonField

consider the following code
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dtCol = new DataColumn();
dtCol = new DataColumn("Name", typeof(string));
dt.Columns.Add(dtCol);
dtCol = new DataColumn("Address", typeof(string));
dt.Columns.Add(dtCol);
dtCol = new DataColumn("Account No", typeof(ButtonField));
dt.Columns.Add(dtCol);
ButtonField bfname = new ButtonField {
HeaderText = "Account No",
DataTextField="Account No",
Text = "Klik",
ButtonType = ButtonType.Link,
CommandName = "ExecuteMe" };
string[] strDataRow = new string[3];
for (int intX = 0; intX < 10; intX++)
{
strDataRow[0] = "Name" + Convert.ToString(intX);
strDataRow[1] = "Address" + Convert.ToString(intX);
strDataRow[2] = bfname.Text; //Error Type of value has a mismatch with column typeCouldn't store <Account No0> in Account No Column. Expected type is ButtonField.
ButtonField btnField = bfname; // No Error but not appear in GridView1
dt.Rows.Add(new object[] {strDataRow[0], strDataRow[1], strDataRow[2]});
//dt.Rows.Add(new object[] { strDataRow[0], strDataRow[1], btnField }); // No Error but not appear in GridView1
/* Error Message on strDataRow[2]
Type of value has a mismatch with column typeCouldn't store <Account No0> in Account No Column. Expected type is ButtonField.
*/
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
How do I store ButtonField in a datarow where the column is set for ButtonField. How the ButtonField.Text appear in each DataRow
And
Is it possible to store string value in a datarow which is the column is set for ButtonField. When the string is click , then the ButtonField.CommandName will execute.
Note* : The GirdView code in ASPX page as follows.
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
Im not sure about your question, but instead of put the button in the DataTable, what I suposed as impossible why not create a GridView and add a TemplateField containing your button.

create custom gridview template fields for a List<>

I have a List of Lists of string . I want to show it to user using a gridview . as number of columns are not known I decided to create gridview fields dynamically . I found some tutorials but all of them use DataTable . I tried to use the same but I have problem with databinding event's "_columnName" :
void field_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();
}
}
as there is no column in list . any suggestion is appreciated .
A much easier way would be to set AutoGenerateColumns to true and use a DataTable as DataSource.
For example ( the aspx can be an empty GridView ):
List<List<String>> data = new List<List<String>>() {
new List<String>(){"Row1_Col1", "Row1_Col2", "Row1_Col3"},
new List<String>(){"Row2_Col1", "Row2_Col2", "Row2_Col3"},
new List<String>(){"Row3_Col1", "Row3_Col2", "Row3_Col3"},
new List<String>(){"Row4_Col1", "Row4_Col2", "Row4_Col3"},
new List<String>(){"Row5_Col1", "Row5_Col2", "Row5_Col3"},
};
var tbl = new DataTable();
int maxFieldCount = data.Max(l => l.Count);
for (int i = 1; i <= maxFieldCount; i++)
tbl.Columns.Add("Column" + i);
foreach (var list in data)
{
DataRow newRow = tbl.Rows.Add();
newRow.ItemArray = list.ToArray();
}
now it can be used as DataSource of the GridView:
GridView1.DataSource = tbl;
GridView1.DataBind();

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.

Resources