How to display row number in gridview - c#

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

Related

Add empty row above the header row in datatable

I followed this Adding new row to datatable's top to add the empty row but even if my index at 0 it will still not adding the empty row above the header at my datatable.
I tried this
DataRow blankRow = dt.NewRow(); dt.Rows.InsertAt(blankRow, 0);
This my code
public void filldatagridview(ExcelWorksheet workSheet)
{
DataTable dt = new DataTable();
//Create the data column
for (int col = workSheet.Dimension.Start.Column; col <= workSheet.Dimension.End.Column; col++)
{
dt.Columns.Add(col.ToString());
}
for (int row = 12; row <= 26; row++)
{
DataRow newRow = dt.NewRow(); //Create a row
int i = 0;
for (int col = workSheet.Dimension.Start.Column; col <= workSheet.Dimension.End.Column; col++)
{
newRow[i++] = workSheet.Cells[row, col].Text;
}
dt.Rows.Add(newRow);
}
dt.Columns.RemoveAt(0); //remove No
dt.Columns.RemoveAt(0); //remove article
//Get BookCode
using (SqlConnection conn = new SqlConnection("Server con.."))
using (SqlCommand cmd = new SqlCommand(null, conn))
{
StringBuilder sb = new StringBuilder("SELECT InvtID AS BOOKCODE FROM InventoryCustomer WHERE Barcode In (");
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i != 0) sb.Append(",");
string name = "#P" + i;
cmd.Parameters.AddWithValue(name, dt.Rows[i]["3"]);
sb.Append(name);
}
sb.Append(")");
cmd.CommandText = sb.ToString();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dt.DefaultView.Sort = "BOOKCODE";
dt = dt.DefaultView.ToTable();
dt.Columns["BOOKCODE"].SetOrdinal(0);
dataGridView2.DataSource = dt;
}
}
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
You can try this. As the DataTable is empty, adding a row automatically adds it at 0th index:
DataRow row = dt.NewRow();
dt.Rows.Add(row);
Or you can do this:
DataRow blankRow = dt.NewRow();
for (int temp = 0; temp < 10; temp++) // here 10 is number of columns
{
blankRow[temp] = ""; // use appropriate data type,
}
dt.Rows.InsertAt(blankRow, 0);
Update:
On DataBound event before adding a datasource:
GridViewRow headerRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
TableHeaderCell headerCell = new TableHeaderCell();
headerCell.Text = "headercol1”;
headerCell.ColumnSpan = 2;
headerRow.Controls.Add(headerCell);
headerCell = new TableHeaderCell();
headerCell.ColumnSpan = 2;
headerCell.Text = "headercol2”;
headerRow.Controls.Add(headerCell);
dataGridView2.HeaderRow.Parent.Controls.AddAt(0, headerRow);
This assumes you have a gridview with 4 columns. I gave 2 colspace to headercol1 and 2 colspace to headercol2

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 dynamically add gridview

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

Best way add a new column with sequential numbering in an existing data table

I have a non empty datatable . What is the best way to add another column to it that has sequential numbering starting from 1.
I tried the following code. But did not work.
DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.DataType = typeof(Int32);
dt.Columns.Add(dc);
Will setting any expression help in this scenario ?
Thanks in Advance
I think you could achieve that by using a 2nd "helper" data table that would contain just an auto-increment field and then you populate/merge it with the existing data, something like this:
DataTable dtIncremented = new DataTable(dt.TableName);
DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.DataType = typeof(Int32);
dtIncremented.Columns.Add(dc);
dtIncremented.BeginLoadData();
DataTableReader dtReader = new DataTableReader(dt);
dtIncremented.Load(dtReader);
dtIncremented.EndLoadData();
And then you would just return dtIncremented table instead of the original dt. Not an elegant solution but should work.
below code worked for me
Code is Edited
// Added temp rows so that this solution can mimic actual requirement
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("Col");
dt.Columns.Add(dc1);
for(int i=0;i<10;i++)
{
DataRow dr = dt.NewRow();
dr["Col"] = i.ToString();
dt.Rows.Add(dr);
}
// Added new column with Autoincrement,
DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.DataType = typeof(Int32);
// Handeled CollectionChanged event
dt.Columns.CollectionChanged += new CollectionChangeEventHandler(Columns_CollectionChanged);
dt.Columns.Add(dc);
// After column added demostratation
DataRow dr1 = dt.NewRow();
dt.Rows.Add(dr1);
void Columns_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
DataColumn dc = (e.Element as DataColumn);
if (dc != null && dc.AutoIncrement)
{
long i = dc.AutoIncrementSeed;
foreach (DataRow drow in dc.Table.Rows)
{
drow[dc] = i;
i++;
}
}
}
You'll have to build a whole new datatable for this and manually deep-copy each row one by one from the old table to the new. Sorry.

Categories