How to dynamically add gridview - c#

I have to dynamically add multiple gridview in ASP.net. There are no of gridview are genereated on the basis of selection.

If I have not understood wrong from title that add multiple grid view dynamically means want to add grid view from code behind at run time.
As GridView is a class in ASP.NET C# and we can create object of it and set its properties just like other class object like follows:
GridView objGV = new GridView();
objGV .AutoGenerateColumns = false;
and can add columns of different type like BoundField and TemplateField from code Like follows:
BoundField field = new BoundField();
field.HeaderText = "Column Header";
field.DataField = Value;
objGV .Columns.Add(field);
and finally can add this grid view object on .aspx under any container control like panel.
PanelId.Controls.Add(objGV );
For adding multiple grid instance just iterate above code in loop like:
for(int i=0;i<yourConditionCount;i++)
{
GridView objGV = new GridView();
objGV.ID="GV"+i; // ID of each grid view must be unique
// your code logic to set properties and events for grid view
PanelId.Controls.Add(objGV );
}
Hope I understood your requirement correctly and my explanation will be helpful for you.

private void BindDynaicGrd()
{
//instance of a datatable
DataTable dt = new DataTable();
//instance of a datarow
DataRow drow;
//creating two datacolums dc1 and dc2
DataColumn dc1 = new DataColumn("Code", typeof(string));
DataColumn dc2 = new DataColumn("Name", typeof(string));
//adding datacolumn to datatable
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
if (grd.Rows.Count > 0)
{
foreach (GridViewRow gvr in grdSites.Rows)
{
CheckBox chk_Single = (CheckBox)gvr.FindControl("chkSingle");
if (chk_Single.Checked == true)
{
Label lbl_Code = (Label)gvr.FindControl("lblCode");
Label lbl_Name = (Label)gvr.FindControl("lblName");
//instance of a datarow
drow = dt.NewRow();
//add rows to datatable
//add Column values
drow = dt.NewRow();
drow["Code"] = lbl_Code.Text;
drow["Name"] = lbl_Name.Text.ToString();
dt.Rows.Add(drow);
}
}
}
//set gridView Datasource as dataTable dt.
gridcl.DataSource = dt;
//Bind Datasource to gridview
gridcl.DataBind();
}

<asp:Panel ID="Panel1" runat="server"> </asp:Panel>
DataSet ds = new DataSet();
ds = obj.GetMedicalGridWithAge(MphID, ProductCode);
if(ds.Tables.Count > 0)
{
if (ds.Tables[1].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables.Count; i++)
{
GridView gv = new GridView();
gv.ID = "gv" + (i + 1);
gv.DataSource = ds.Tables[i];
gv.DataBind();
Panel1.Controls.Add(gv);
Label newLine = new Label(); newLine.Text = "<br/>";
Panel1.Controls.Add(newLine);
}
}
else
{
GridView gv = new GridView();
gv.ID = "gv" ;
gv.DataSource = null;
gv.DataBind();
Panel1.Controls.Add(gv);
}
}

Related

How to dynamically populate a gridview where the dataset column length is not static/known [duplicate]

I have to dynamically add multiple gridview in ASP.net. There are no of gridview are genereated on the basis of selection.
If I have not understood wrong from title that add multiple grid view dynamically means want to add grid view from code behind at run time.
As GridView is a class in ASP.NET C# and we can create object of it and set its properties just like other class object like follows:
GridView objGV = new GridView();
objGV .AutoGenerateColumns = false;
and can add columns of different type like BoundField and TemplateField from code Like follows:
BoundField field = new BoundField();
field.HeaderText = "Column Header";
field.DataField = Value;
objGV .Columns.Add(field);
and finally can add this grid view object on .aspx under any container control like panel.
PanelId.Controls.Add(objGV );
For adding multiple grid instance just iterate above code in loop like:
for(int i=0;i<yourConditionCount;i++)
{
GridView objGV = new GridView();
objGV.ID="GV"+i; // ID of each grid view must be unique
// your code logic to set properties and events for grid view
PanelId.Controls.Add(objGV );
}
Hope I understood your requirement correctly and my explanation will be helpful for you.
private void BindDynaicGrd()
{
//instance of a datatable
DataTable dt = new DataTable();
//instance of a datarow
DataRow drow;
//creating two datacolums dc1 and dc2
DataColumn dc1 = new DataColumn("Code", typeof(string));
DataColumn dc2 = new DataColumn("Name", typeof(string));
//adding datacolumn to datatable
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
if (grd.Rows.Count > 0)
{
foreach (GridViewRow gvr in grdSites.Rows)
{
CheckBox chk_Single = (CheckBox)gvr.FindControl("chkSingle");
if (chk_Single.Checked == true)
{
Label lbl_Code = (Label)gvr.FindControl("lblCode");
Label lbl_Name = (Label)gvr.FindControl("lblName");
//instance of a datarow
drow = dt.NewRow();
//add rows to datatable
//add Column values
drow = dt.NewRow();
drow["Code"] = lbl_Code.Text;
drow["Name"] = lbl_Name.Text.ToString();
dt.Rows.Add(drow);
}
}
}
//set gridView Datasource as dataTable dt.
gridcl.DataSource = dt;
//Bind Datasource to gridview
gridcl.DataBind();
}
<asp:Panel ID="Panel1" runat="server"> </asp:Panel>
DataSet ds = new DataSet();
ds = obj.GetMedicalGridWithAge(MphID, ProductCode);
if(ds.Tables.Count > 0)
{
if (ds.Tables[1].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables.Count; i++)
{
GridView gv = new GridView();
gv.ID = "gv" + (i + 1);
gv.DataSource = ds.Tables[i];
gv.DataBind();
Panel1.Controls.Add(gv);
Label newLine = new Label(); newLine.Text = "<br/>";
Panel1.Controls.Add(newLine);
}
}
else
{
GridView gv = new GridView();
gv.ID = "gv" ;
gv.DataSource = null;
gv.DataBind();
Panel1.Controls.Add(gv);
}
}

How to display row number in gridview

I use code below but it didint work.. It didnt show me column with that field.
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
I add my other columns in code behind and meaby it's the problem?
OleDbDataAdapter sqlArchiveData = new OleDbDataAdapter(sql_archive);
DataTable dt = new DataTable();
connProdcc1.Open();
sqlArchiveData.Fill(dt);
foreach (DataColumn column in dt.Columns)
{
BoundField field = new BoundField();
field.DataField = column.ColumnName;
field.HeaderText = column.ColumnName.Replace("_"," ");
field.SortExpression = column.ColumnName;
AggregateGridView.Columns.Add(field);
}
AggregateGridView.DataSource = dt;
AggregateGridView.DataBind();
Does anone have any idea how to do this in other way?
I try to this like below but it's counts my row number after all data I Fill() into a DataTable and then add to each row a number
DataColumn columnIndexRow = new DataColumn();
columnIndexRow.DataType = System.Type.GetType("System.Int32");
columnIndexRow.ColumnName = "id";
dt.Columns.Add(columnIndexRow);
for (int i = 0; i < dt.Rows.Count; i++)
{
// your index is in i
var row = dt.NewRow();
row["id"] = i;
dt.Rows.Add(row);
}
ADD row number field to DataTable
OleDbDataAdapter sqlArchiveData = new OleDbDataAdapter(sql_archive);
DataTable dt = new DataTable();
connProdcc1.Open();
sqlArchiveData.Fill(dt);
dt = AutoNumberedTable(dt);
foreach (DataColumn column in dt.Columns)
{
BoundField field = new BoundField();
field.DataField = column.ColumnName;
field.HeaderText = column.ColumnName.Replace("_"," ");
field.SortExpression = column.ColumnName;
AggregateGridView.Columns.Add(field);
}
AggregateGridView.DataSource = dt;
AggregateGridView.DataBind();
private DataTable AutoNumberedTable(DataTable SourceTable)
{
DataTable ResultTable = new DataTable();
DataColumn AutoNumberColumn = new DataColumn();
AutoNumberColumn.ColumnName="S.No.";
AutoNumberColumn.DataType = typeof(int);
AutoNumberColumn.AutoIncrement = true;
AutoNumberColumn.AutoIncrementSeed = 1;
AutoNumberColumn.AutoIncrementStep = 1;
ResultTable.Columns.Add(AutoNumberColumn);
ResultTable.Merge(SourceTable);
return ResultTable;
}
Hope this might help. :)
Note: I haven't tested this code.
Thanks guys! I just find out the answer. I do something like updating a cell at row index and first column
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i][0] = i;
}

How to add textBox to Winform dataGridView cells

I want to add textBox to my column cells by for loop...
My code:
DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn("No");
dt.Columns.Add(dc);
dc = new DataColumn("Item");
dt.Columns.Add(dc);
dc = new DataColumn("Available Stock");
dt.Columns.Add(dc);
dc = new DataColumn("Quantity");
dt.Columns.Add(dc);
dc = new DataColumn("Price");
dt.Columns.Add(dc);
// Define rows
for (int i = 0; i < count; i++)
{
string no = dtr.Rows[i][0].ToString();
string item = dtr.Rows[i][2].ToString() + " " + dtr.Rows[i][1].ToString();
string A_qty = dtr.Rows[i][3].ToString();
string price = dtr.Rows[i][4].ToString();
dt.Rows.Add(no, item, A_qty,"[i want to add text box here] " ,price);
}
dataGridView1.DataSource = dt;
I want to add textBoxes to 4th column and I want access that one by one.
You can add textBox column to DataGridView instead and loop through DataGridView like
DataTable dt=new DataTable();
dt.Columns.Add("No",typeof(int));
dt.Columns.Add("Item",typeof(string));
dt.Columns.Add("quantity",typeof(int));
dt.Columns.Add("Price",typeof(decimal));
//Add row to the datatable
for (int i = 0; i < count; i++)
{
//Not Sure what dtr is you looping through
string no = dtr.Rows[i][0].ToString();
string item = dtr.Rows[i][1].ToString() + " " + dtr.Rows[i][1].ToString();
string A_qty = dtr.Rows[i][2].ToString();
string price = dtr.Rows[i][3].ToString();
dt.Rows.Add(no, item, A_qty, price);
}
//Create New DataGridViewTextBoxColumn
DataGridViewTextBoxColumn textboxColumn=new DataGridViewTextBoxColumn();
//Bind DataGridView to Datasource
dataGridView1.datasource=dt;
//Add TextBoxColumn dynamically to DataGridView
dataGridView1.Columns.Add(textboxColumn);
//Loop through DataGridView
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//Do your task here
string fourthColumn = row.Cells[4].Value.toString();
}
Not sure. But hope this code will help you. Just add column of type textbox to your datatable.
DataTable table = new DataTable();
DataColumn col = new DataColumn("Name", typeof(TextBoxBase));
table.Columns.Add(col);

Is it possible to put temporary data into datagridview without any datasource

I want to put my data into data grid view, by manually adding columns in it, so how can i do that,please help me.
Thank You in Advance.
Try the following that might solve your problem:
Ensure that the gridview(assuming he ID="gridview1") is in the markup and that AutoGenerateColumns="True"
DataTable dataTable = new dataTable();
dataTable.Columns.Add("Column1");
dataTable.Columns.Add("Column2");
dataTable.Columns.Add("Column3");
DataRow dataRow = dataTable.NewRow();
dataRow["Column1"] = "";
dataRow["Column2"] = "";
dataRow["Column3"] = "";
dataTable.Rows.Add(dataRow);
gridview1.DataSource = datatable;
gridview1.DataBind();
What about something like:
var grd = new GridView();
grd.AutoGenerateColumns = false;
BoundField field = new BoundField();
field.DataField = "CustomerName";
field.HeaderText = Resources.GlobalResources.Customer;
DataControlField col = field;
grd.Columns.Add(col);
grd.DataSource = sortedCustomers;
grd.DataBind();

Why DataColumn.Caption doesn't work?

I am trying to create a DataTable and bind it to a DataGridView. It works, but I can't set columns headers via the Caption property. It displays headers using the ColumnName ("City") instead. MSDN says that
"You can use the Caption property to display a descriptive or friendly
name for a DataColumn."
Here is my code:
DataColumn dc = new DataColumn("City", typeof(string));
dc.Caption = "Город";
DataTable dt = new DataTable();
dt.Columns.Add(dc);
DataRow row = dt.NewRow();
row["City"] = "Moscow";
dt.Rows.Add(row);
datagridview.DataSource = dt;
Well, MSDN is right. That is what the Caption property is for. However, that doesn't mean that control makers have to use the caption property. In this case, Microsoft didn't do that (although they really should have). You can modify your code to this though:
///snip
dataGridView1.DataSource = dt;
foreach (DataGridViewColumn col in dataGridView1.Columns) {
col.HeaderText = dt.Columns[col.HeaderText].Caption;
}
I think when you bind to a DataTable, the DataGridView does not use the Caption property. It only works when you bind to a DataSet.
You can modify the column headers manually like this:
dataGridView.Columns[i].HeaderText = dt.Columns[i].Caption;
You should try this:
datagridView.Columns[0].HeaderText = "Title Goes Here.";
You may do this for the number of columns you have added. Only the index will change.
in vb.net code :
Dim dt As New DataTable
dt.Columns.Add("col1").Caption = "Your Header Text"
'and add more columns with .caption
GridView1.DataSource = dt
For Each col As DataColumn In dt.Columns
GridView1.Columns(col.ColumnName).HeaderText = col.Caption
Next
#aquinas, this works for me
foreach (DataGridViewColumn col in dataGridView1.Columns) {
col.HeaderText = dt.Columns[col.Name].Caption;
}
foreach (DataTable dataTable in dataSet.Tables)
{
form1.Controls.Add(new LiteralControl(String.Format("<h1>{0}</h1>", dataTable.TableName)));
GridView grid = new GridView();
grid.AllowPaging = false;
grid.AutoGenerateColumns = false;
foreach (DataColumn col in dataTable.Columns)
{
grid.Columns.Add(new BoundField { DataField = col.ColumnName, HeaderText = col.Caption });
}
grid.DataSource = dataTable;
grid.DataBind();
form1.Controls.Add(grid);
}

Categories