Add empty row above the header row in datatable - c#

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

Related

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

Storing filtered rows of dataGridView in a DataTable

I have a RadGridView control in my form. I bind DataGriView by one parameter by a search control. I use this code to store my selected rows in a DataTable and show in a report:
DataTable table = new DataTable("dt1");
foreach (Telerik.WinControls.UI.GridViewDataColumn column in radGridView1.Columns)
{
table.Columns.Add(column.Name, typeof(string));
}
for (int i = 0; i < radGridView1.Rows.Count; i++)
{
table.Rows.Add();
for (int j = 0; j < radGridView1.Columns.Count; j++)
{
table.Rows[i][j] = radGridView1.Rows[i].Cells[j].Value;
}
}
DataSet ds = new DataSet();
ds.Tables.Add(table);
StiReport stiReport = new StiReport();
stiReport.Load("Report.mrt");
stiReport.RegData(table);
StiOptions.Viewer.Windows.ShowPageDesignButton = false;
StiOptions.Viewer.Windows.ShowOpenButton = false;
//stiReport.Design();
stiReport.Show();
This code works, but when I use filter of RadDataGridView for selecting rows, the above code doesn't work good and all rows are displayed. How can change this code for storing only filtered rows in a DataTable.
Try making this change and you should get the desired result
DataTable table = new DataTable("dt1");
foreach (Telerik.WinControls.UI.GridViewDataColumn column in radGridView1.Columns)
{
table.Columns.Add(column.Name, typeof(string));
}
for (int i = 0; i < radGridView1.Rows.Count; i++)
{
table.Rows.Add();
for (int j = 0; j < radGridView1.Columns.Count; j++)
{
table.Rows[i][j] = radGridView1.Rows[i].Cells[j].Value;
}
}
DataSet ds = new DataSet();
ds.Tables.Add(table);
var dv = ds.Tables[0].DefaultView;
var strExpr = "ItemID = 1"; //Change accordingly
dv.RowFilter = strExpr;
var newDT = dv.ToTable();
StiReport stiReport = new StiReport();
stiReport.Load("Report.mrt");
stiReport.RegData(newDT);
StiOptions.Viewer.Windows.ShowPageDesignButton = false;
StiOptions.Viewer.Windows.ShowOpenButton = false;
//stiReport.Design();
stiReport.Show();
where strExpr should be the filtering expression that you want to use. Hope this works for you, Cheers

How to append row from one dataset to another dataset?

I want to add one row from dataset ds to dc every time. and I want to keep updating the Gridview to bigger the table. But when I try it in my code. the Gridview can only display one row according to what i input in the textbox.
public partial class TestGridview : System.Web.UI.Page
{
int count = 0;
DataSet dc = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
string text = TextBox1.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["XMLConnectionString"].ConnectionString);
// Create the command object
string str = "SELECT * FROM XML WHERE [Part_Numbber] = #textInput";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.AddWithValue("textInput", text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "XML");
if (count == 0)
{
dc = ds.Clone();
count ++;
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i].ItemArray[0].ToString() != "NULL")
{
dc.Tables[0].ImportRow(ds.Tables[0].Rows[i]);
}
}
GridView1.DataSource = dc;
GridView1.DataBind();
}
}
You can make use of below code to append rows from 1 DT to other final DT. LikeWise
foreach (DataRow dataRow in dt2.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}
foreach (DataRow dataRow in dt3.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}
foreach (DataRow dataRow in dt4.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}

drop down list have no items on adding new row in grid view through button click

I have a Grid view containing 3 drop down lists and 3 text boxes each and a button. my drop down lists are populating data from data base. When i click on the button to add new row after filling the initial row. it sets the first row values fine and adds a new row. but the new row has no items in drop down lists this is my problem. secondly when i click the button again for adding third row it even looses the value of first row filled and same problem comes with first row that there are no items in drop down lists.
void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dt.Columns.Add(new DataColumn("Column4", typeof(string)));
dt.Columns.Add(new DataColumn("Column5", typeof(string)));
dt.Columns.Add(new DataColumn("Column6", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dr["Column5"] = string.Empty;
dr["Column6"] = string.Empty;
dt.Rows.Add(dr);
//dr = dt.NewRow();
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox and dropdown lists values
DropDownList list1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = list1.SelectedItem.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = list2.SelectedItem.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column4"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column5"] = list3.SelectedItem.Text;
dtCurrentTable.Rows[i - 1]["Column6"] = box3.Text;
Session["list1"] = dtCurrentTable.Rows[i - 1]["Column1"];
Session["list2"] = dtCurrentTable.Rows[i - 1]["Column2"];
Session["list3"] = dtCurrentTable.Rows[i - 1]["Column5"];
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
void SetPreviousData()
{
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 list1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("TextBox3");
list1.DataSource = bindddl();
list1.DataValueField = "Item_name";
list1.DataTextField = "Item_name";
list1.DataBind();
list1.Items.Insert(0, new ListItem("--Select--", "0"));
list2.DataSource = binddd2();
list2.DataValueField = "Sub_item";
list2.DataTextField = "Sub_item";
list2.DataBind();
list2.Items.Insert(0, new ListItem("--Select--", "0"));
list3.Items.Insert(0, new ListItem("--Select--", "0"));
list3.Items.Insert(1, new ListItem("Yes", "1"));
list3.Items.Insert(2, new ListItem("No", "2"));
box1.Text = dt.Rows[i]["Column3"].ToString();
box2.Text = dt.Rows[i]["Column4"].ToString();
box3.Text = dt.Rows[i]["Column6"].ToString();
list1.Text = Session["list1"].ToString();
list2.Text = Session["list2"].ToString();
box1.Text = dt.Rows[i]["Column3"].ToString();
box2.Text = dt.Rows[i]["Column4"].ToString();
list3.Text = Session["list3"].ToString();
box3.Text = dt.Rows[i]["Column6"].ToString();
// Response.Write(Session["list1"]);
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
Fillcombo();
Fillcombo1();
Fillcombo2();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
Fillcombo();
Fillcombo1();
Fillcombo2();
}
Fillcombo,Fillcombo1 are functions which are populating Drop down lists 1,2 through data base Fillcombo2 is populating it has two items yes' and 'no'.
My Fillcombo functions are like this
try
{
string connString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (var conn = new SqlConnection(connString))
using (var cmd = conn.CreateCommand())
{conn.Open();
SqlCommand cmdstr = new SqlCommand("SELECT [Sub_item] FROM [ADS].[dbo].[Accounts_heads_data]", conn);
// SqlCommand cmdstr = new SqlCommand("SELECT * FROM [ADS].[dbo].[Accounts_heads_data] ", conn);
SqlDataAdapter da2 = new SqlDataAdapter(cmdstr);
DataSet ds2 = new DataSet();
da2.Fill(ds2);
DropDownList DropDownList2 = (DropDownList)Gridview1.Rows[0].FindControl("DropDownList2");
DropDownList2.DataValueField = ds2.Tables[0].Columns["Sub_item"].ToString();
DropDownList2.DataTextField = ds2.Tables[0].Columns["Sub_item"].ToString();
DropDownList2.DataSource = ds2.Tables[0];
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem("--Select--", "0"));
ViewState["fc1"] = ds2;
conn.Close();
}
}
catch (Exception ex)
{
Label1.Visible = true;
}
}
check by comenting
SetPreviousData(); line from
AddNewRowToGrid function
OR
in AddNewRowToGrid function only set data for new row and call SetPreviousData(); function in first row of AddNewRowToGrid function.
I compiled your code with some test data and changed the code a bit. Try following and see.
void AddNewRowToGrid()
{
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 0; i < dtCurrentTable.Rows.Count-1; i++)
{
DropDownList list1 = (DropDownList)Gridview1.Rows[i].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[i].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[i].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[6].FindControl("TextBox3");
dtCurrentTable.Rows[i]["Column1"] = list1.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column2"] = list2.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column3"] = box1.Text;
dtCurrentTable.Rows[i]["Column4"] = box2.Text;
dtCurrentTable.Rows[i]["Column5"] = list3.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column6"] = box3.Text;
}
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
void SetPreviousData()
{
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 list1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("TextBox3");
Fillcombo();
Fillcombo1();
Fillcombo2();
box1.Text = dt.Rows[i]["Column3"].ToString();
box2.Text = dt.Rows[i]["Column4"].ToString();
box3.Text = dt.Rows[i]["Column6"].ToString();
if (i < dt.Rows.Count - 1)
{
list1.ClearSelection();
list1.Items.FindByText(dt.Rows[i]["Column1"].ToString()).Selected = true;
list2.ClearSelection();
list2.Items.FindByText(dt.Rows[i]["Column2"].ToString()).Selected = true;
list3.ClearSelection();
list3.Items.FindByText(dt.Rows[i]["Column5"].ToString()).Selected = true;
}
rowIndex++;
}
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}

How to display rows as columns in DataGridView?

I'm trying to display set of data which have retrieved from the sql database using a datagridview in VS 2008. But I need to display data vertically rather than horizontally. This is what I have done at the beginning.
con.Open();
SqlCommand cmd = new SqlCommand("proc_SearchProfile", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#scute_id", SqlDbType.VarChar, (10)).Value = val;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet dset = new DataSet();
adapt.Fill(dset, "Profile");
this.dataGridView1.DataSource = dset;
this.dataGridView1.DataMember = "Profile";
I searched and read a few threads but none of those work. Can anyone help me on displaying retrieved data in a datagridview vertically?
Try this:
var tbl = dset.Tables["Profile"]:
var swappedTable = new DataTable();
for (int i = 0; i <= tbl.Rows.Count; i++)
{
swappedTable.Columns.Add(Convert.ToString(i));
}
for (int col = 0; col < tbl.Columns.Count; col++)
{
var r = swappedTable.NewRow();
r[0] = tbl.Columns[col].ToString();
for (int j = 1; j <= tbl.Rows.Count; j++)
r[j] = tbl.Rows[j - 1][col];
swappedTable.Rows.Add(r);
}
dataGridView1.DataSource = swappedTable;

Categories