I am manually creating a datatable to apply it to a gridview and the textbox column is not showing up. The other columns work just fine but I need to create a column with inputtable text boxes.
Cheers,
Chris
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int numPrizes = GetNumPrizes();//if there are voided prizes.
DataTable dt = new DataTable();
gvTournamentData.Columns.Clear();
//PrizeNumber
//Add the columns to the grid view
BoundField PrizeNumberBF = new BoundField();
PrizeNumberBF.DataField = "PrizeNumber";
PrizeNumberBF.SortExpression = "PrizeNumber";
PrizeNumberBF.HeaderText = "";
gvTournamentData.Columns.Add(PrizeNumberBF);
dt.Columns.Add("PrizeNumber");
//Place
//Add the columns to the grid view
BoundField PlaceBF = new BoundField();
PlaceBF.DataField = "Place";
PlaceBF.SortExpression = "Place";
PlaceBF.HeaderText = "Place";
gvTournamentData.Columns.Add(PlaceBF);
dt.Columns.Add("Place", typeof(String));
DataTable dtPlaces = GetPlaces(1043); //hard coded for now
////PrizeName //BFOP Prize
//Add the columns to the grid view
BoundField PrizeNameBF = new BoundField();
PrizeNameBF.DataField = "BFOP Prize";
PrizeNameBF.SortExpression = "BFOP Prize";
PrizeNameBF.HeaderText = "BFOP Prize";
gvTournamentData.Columns.Add(PrizeNameBF);
dt.Columns.Add("BFOP Prize", typeof(String));
DataTable dtPrizeNames = GetPrizeNames(1043); //hard coded for now
////NickName
dt.Columns.Add("NickName", typeof(TextBox));
numPrizes = 7; //hard coded for now
for (int index = 1; index <= numPrizes; index++)
{
// Start at Prize one instead of Prize zero
string ID = index.ToString();
DataRow row = dt.NewRow();
row["PrizeNumber"] = ID + ")";
row["Place"] = dtPlaces.Rows[index - 1]["Place"];
row["BFOP Prize"] = dtPrizeNames.Rows[index - 1]["PrizeName"];
//TextBox nicknameTB = new TextBox();
//nicknameTB.Text = ID + ")";
//row["NickName"] = nicknameTB;
/* for (int x = 0; x < numCols; x++)
{
PopulatePrizeNameLabel(ID);
PopulateAddButton(ID);
}*/
dt.Rows.Add(row);
}
gvTournamentData.DataSource = dt;
gvTournamentData.DataBind();
gvTournamentData.Visible = true;
}
}
Why not use TemplateColumn in your form page
Example:
<asp:GridView>
<Columns>
<asp:TemplateColumn HeaderText="Place">
<ItemTemplate>
<%#Eval("Place")%>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="NickName">
<ItemTemplate>
<asp:TextBox ID="txt_NickName" runat="server" Width="85px" Text='<%#Eval("NickName")%>'>
</asp:TextBox>
</ItemTemplate>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:GridView>
So you lay out your template you would want to bind to. The approach above is more flexible.
So when you come down to binding your data to the grid view:
gvTournamentData.DataSource = dt;
gvTournamentData.DataBind();
Then it will render all those fields to a template.
Use this link as a reference: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
Related
I have 2 dropdownlists in grid view. The selection of the first one (EqpCatDDL) will determine what values the second one (DescripDDL) will be populated with.
However, everytime I click the Add New Row button, the DescripDDL dropdownlist clears up. I don't know why it does that. The following is the code:
aspx:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="Gridview1" runat="server" ShowFooter="True" AutoGenerateColumns="False"
OnRowDataBound="Gridview1_RowDataBound">
<Columns>
<asp:BoundField DataField="S/N" HeaderText="S/N" />
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:DropDownList ID="EqpCatDDL" runat="server" AutoPostBack="true" OnSelectedIndexChanged="EqpCatDDL_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:DropDownList ID="DescripDDL" runat="server" AutoPostBack="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<contenttemplate>
<asp:Button ID="ButtonAdd" onclick="ButtonAdd_Click" runat="server" Text="Add New Row" />
</contenttemplate>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
c#:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow(); //create a datatable to bind to GridView
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("S/N", 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)));
dr = dt.NewRow();
dr["S/N"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
GridViewRow row = (GridViewRow)((sender as Button).NamingContainer);
Button btn = row.FindControl("ButtonAdd") as Button;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(btn);
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
//extract the TextBox values
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//Locate controls in GridView
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
//Save control values into DataTable
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["S/N"] = i + 1;
drCurrentRow["Column1"] = ddl1.SelectedValue.ToString();
drCurrentRow["Column2"] = ddl2.SelectedValue.ToString();
drCurrentRow["Column3"] = box3.Text;
drCurrentRow["Column4"] = box4.Text;
dtCurrentTable.Rows[rowIndex]["Column1"] = ddl1.SelectedValue.ToString();
dtCurrentTable.Rows[rowIndex]["Column2"] = ddl2.SelectedValue.ToString();
dtCurrentTable.Rows[rowIndex]["Column3"] = box3.Text;
dtCurrentTable.Rows[rowIndex]["Column4"] = box4.Text;
rowIndex++;
}
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState
ViewState["CurrentTable"] = dtCurrentTable;
//Rebind the Grid with the current data
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData(); //Set Previous Data from DataTable to GridView on Postbacks from Add New Row button click
}
private 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-1); i++)
{
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
ddl1.Text = dt.Rows[i]["Column1"].ToString();
ddl2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
rowIndex++;
}
}
}
}
//Populate Item Name dropdownlist from EqpCat column in EqpCategory table
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
//Find the DropDownList in the Row
DropDownList EqpCatDDL = (e.Row.FindControl("EqpCatDDL") as DropDownList);
SqlCommand cmd1 = new SqlCommand("SELECT DISTINCT EqpCat FROM EqpCategory", connection);
cmd1.Connection.Open();
SqlDataReader ddlValues1;
ddlValues1 = cmd1.ExecuteReader();
EqpCatDDL.DataSource = ddlValues1;
EqpCatDDL.DataTextField = "EqpCat";
EqpCatDDL.DataValueField = "EqpCat";
EqpCatDDL.DataBind();
cmd1.Connection.Close();
cmd1.Connection.Dispose();
//Add Default Item in the DropDownList
EqpCatDDL.Items.Insert(0, new ListItem("--Select--"));
}
}
//Populate Description dropdownlist based on selected value of Item Name dropdownlist
protected void EqpCatDDL_SelectedIndexChanged(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
GridViewRow gvr = (GridViewRow)((DropDownList)sender).Parent.Parent;
DropDownList EqpCatDDL = gvr.FindControl("EqpCatDDL") as DropDownList;
DropDownList DescripDDL = gvr.FindControl("DescripDDL") as DropDownList;
string cate = EqpCatDDL.SelectedValue.ToString();
SqlCommand cmd2 = new SqlCommand("SELECT Description FROM EqpCategory WHERE EqpCat = '" + cate + "'", connection);
cmd2.Connection.Open();
SqlDataReader ddlValues2;
ddlValues2 = cmd2.ExecuteReader();
DescripDDL.DataSource = ddlValues2;
DescripDDL.DataTextField = "Description";
DescripDDL.DataValueField = "Description";
DescripDDL.DataBind();
cmd2.Connection.Close();
cmd2.Connection.Dispose();
//Add Default Item in the DropDownList
DescripDDL.Items.Insert(0, new ListItem("--Select--"));
}
I am currently using: Visual Studio 2010 with SSMS 2008
Just modify your SetPreviousData Function
private 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 - 1); i++)
{
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
ddl1.SelectedValue = dt.Rows[i]["Column1"].ToString();
string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd2 = new SqlCommand(""SELECT Description FROM EqpCategory WHERE EqpCat = '" + Convert.ToInt32(ddl1.SelectedValue) + "'", connection);
cmd2.Connection.Open();
SqlDataReader ddlValues2;
ddlValues2 = cmd2.ExecuteReader();
ddl2.DataTextField = "Description";
ddl2.DataValueField = "Description";
ddl2.DataSource = ddlValues2;
ddl2.DataBind();
cmd2.Connection.Close();
cmd2.Connection.Dispose();
ddl2.SelectedValue = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
rowIndex++;
}
}
}
}
Use SelectedValue (https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedvalue(v=vs.110).aspx) instead of text to set the selected item.
E.g.:
ddl1.SelectedValue = dt.Rows[i]["Column1"].ToString();
ddl2.SelectedValue = dt.Rows[i]["Column2"].ToString();
This is my program that page load the gridview and retrieve the database record to textbox and i put a add new button wish to add new row exactly like that row but the textbox is empty.
I wanted to create a new row in GridView while click add new button while my TextBox is retrieve data from database. I try to run the code but it is nothing happen when i click the button. Hope someone may help. Thanks.
My front end code
<Columns>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Font-Bold="true" Font-Size="Medium">Name</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" CssClass="NormalInputTextField" Text='<%#Eval("SLMN") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Button ID="BtnDelete" runat="server" Text="Delete" CssClass="btn btn-primary" CommandName="remove" CommandArgument='<%# Container.DataItemIndex %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField FooterStyle-BorderStyle="None" HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Button ID="BtnSearch2" runat="server" Text="Search" CssClass="btn btn-primary" CommandName="ViewComments" OnClientClick="javascript:saveData(this,'grid')"/>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" BorderStyle="None"/>
<FooterTemplate>
<asp:Button ID="BtnAdd" runat="server" Text="Add New Row" CssClass="btn btn-primary" OnClick="ButtonAdd_Click"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
My back end code
private void AddNewRowToGrid()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dr = dt.NewRow();
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dt.Rows.Add(dr);
}
My onclick event to call add new function
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
My gridview tag
<grd:MultiSelectGridView ID="grid2" runat="server" Width="500px"
CssClass="paging_gridview" AllowPaging="True"
AutoGenerateColumns ="false" PageSize="10" PagerType="Custom"
ShowFooter="true" OnRowDeleting="grid2_RowDeleting"
MultiSelectDataKeyName="Urid,Name" ShowHeaderWhenEmpty="true"
MultiSelectColumnIndex="0" EnableMultiSelect="false" GridLines="None" BorderStyle="None" OnRowCommand="grid2_RowCommand"
>
i bind my record to gridview by page load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Loadgrid();
}
}
private void Loadgrid()
{
string branch = txtBranch.Text.Trim();
string name = txtName.Text.Trim();
string sql = "SELECT * FROM fcs_cotmdl WHERE TMDL= '" + name + "'AND CONO='" + branch + "' ";
SqlDataSource2.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr_epsi"].ConnectionString;
SqlDataSource2.ConnectionString = SqlDataSource2.ConnectionString.Replace("Provider=OraOLEDB.Oracle.1;", "");
SqlDataSource con = new SqlDataSource();
SqlDataSource2.SelectCommand = sql;
grid2.DataSourceID = "SqlDataSource2";
grid2.DataBind();
}
Following tutorial details the exact same scenario. Please refer to it.
Adding Dynamic Rows to Gridview on Button Click
private 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 values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
//Instead of all the textboxes, use the button as you require.
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
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();
}
And then the SetPreviousData() Function:
private 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++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
Then inside your Click Event:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
From your Load grid method you should retrieve the data as a data table and bind to grid. And save in in session. Like this:
private void Loadgrid()
{
var dt = new DataTable();
using (var conn = new SqlConnection (ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString()))
{
var command = new SqlCommand();
command.Connection = conn;
command.CommandText = "SELECT * FROM [dbo].[T1]";
command.CommandType = CommandType.Text;
using (var adaptor = new SqlDataAdapter(command))
{
if (conn.State == ConnectionState.Closed) conn.Open();
adaptor.Fill(dt);
if (conn.State == ConnectionState.Open) conn.Close();
}
}
Session["ss"] = dt;
grid2.DataSource = dt;
grid2.DataBind();
}
private void AddNewRowToGrid()
{
DataTable dt = (DataTable) Session["ss"];
DataRow dr = null;
DataRow newBlankRow1 = dt.NewRow();
dt.Rows.Add(newBlankRow1);
grid2.DataSource = dt;
grid2.DataBind();
Session["ss"] = dt;
}
After add an empty row also you need to bind data to grid again.
I need to set number of row in data grid view (like identity in sql) in winforms. i am dynamically adding columns and rows in grid view. any idea.
To display text in the row header you can use the Row.HeaderCell.Value as shown below:
void dataGridView1_DataBindingComplete(object sender,
DataGridViewBindingCompleteEventArgs e)
{
DataGridView gridView = sender as DataGridView;
if (null != gridView)
{
foreach (DataGridViewRow r in gridView.Rows)
{
gridView.Rows[r.Index].HeaderCell.Value =
(r.Index + 1).ToString();
}
}
}
This only displays the row number of the new row when the user begins typing in it. Not sure if there is a simple way of always showing the row number on the new row.
Another best way for asp.net application.Here is a link http://www.devcurry.com/2010/01/add-row-number-to-gridview.html
Just add the following tags to your section of your GridView
<Columns>
<asp:TemplateField HeaderText="RowNumber">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
...
</Columns>
Method 1:
//You can also use below code
this.DataGridView1.Rows[e.RowIndex].Cell[0].value =e.RowIndex +1;
//get total number of rows
this.DataGridView1.Rows.Count;
Method 2:
for (int i = 0; i < SensorGridView.Rows.Count; i++)
{
DataGridViewRowHeaderCell cell = SensorGridView.Rows[i].HeaderCell;
cell.Value = (i + 1).ToString();
SensorGridView.Rows[i].HeaderCell = cell;
}
Method 3:
void GridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
this.GridView.Rows[e.RowIndex].Cells[0].Value
= (e.RowIndex + 1).ToString();
}
Why not like this way. Build a datatable first and then bind to grid like below
DataTable tbl = new DataTable();
Datacolumn dc = new Datacolumn("ID");
Datacolumn dc1 = new Datacolumn("col1");
Datarow dr = tbl.NewRow();
dr[dc] = "123";
dr[dc1] = "SomeData";
tbl.Rows.Add(dr);
DataGridView.DataSource = tbl;
I have a ListBox, on_button click, I want all the items in the ListBox to be displayed as headers in the GridView.
Here is the code that i have tried :
protected void DONE4_Click(object sender, EventArgs e)
{
Panel7.Visible = true;
DataTable dt = new DataTable();
for (int i = 0; i < ListBox1.Items.Count; i++)
{
dt.Columns.Add(ListBox1.Items[i].ToString());
}
GridView2.DataSource = dt;
GridView2.DataBind();
foreach (GridViewRow grdRow in GridView2.Rows)
{
DropDownList bind_dropdownlist = new DropDownList(); // defining the property of the DropDownList as bind_dropdownlist
bind_dropdownlist = (DropDownList)(GridView2.Rows[grdRow.RowIndex].Cells[0].FindControl("Pro_List")); // finding the DropDownList from the gridiew for binding
SqlDataAdapter mydata = new SqlDataAdapter("SELECT DISTINCT Profile_Instance FROM Profile_Master", con);
DataSet dset = new DataSet(); // binding the DropDownList with the dataset ds
mydata.Fill(dset, "Table");
bind_dropdownlist.DataSource = dset;
bind_dropdownlist.DataTextField = "Profile_Instance"; // set the DropDownList's DataTextField as designation which display the designation in the dropdownlist after fetching the data from database
bind_dropdownlist.DataBind();
bind_dropdownlist.Items.Insert(0, new ListItem("---Choose Profile---", "-1"));
}
}
I want all the items in the ListBox to be displayed as header field in a GridView.
The code above gives no errors, but when run it does not work. Can anyone kindly help me with this?
Here is my Design code for the GridView:
<asp:Panel ID="Panel7" runat="server">
<asp:GridView ID="GridView2" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" style="text-align: center; font-size: small">
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:DropDownList ID="Pro_List" runat="server">
<asp:ListItem>--Select--</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
After setting the DataSource, call the DataBind method and see what happens
GridView2.DataSource = dt;
GridView2.DataBind();
Edit
The below code works just fine. Tested.
If you do not have data in the Grid, it won't show anything even the headers unless you give an EmptyText field property value for the grid.
DataTable dt = new DataTable();
DataRow rw = default(DataRow);
for (int i = 0; i < ListBox1.Items.Count; i++)
{
dt.Columns.Add(ListBox1.Items[i].ToString(),
System.Type.GetType("System.String"));
}
//Simply adding 10 rows
//Replace this hard coded loop with your looping
// over your data to add rows.
for (int j = 0; j < 10; j++)
{
rw = dt.NewRow();
for (int i = 0; i < ListBox1.Items.Count; i++)
{
rw[ListBox1.Items[i].ToString()] = "Hello there";
}
dt.Rows.Add(rw);
}
GridView1.DataSource = dt;
GridView1.DataBind();
The working sample is available in this link.
This is very interesting..
I want to have multiple gridviews in a panel. and the number of gridviews is not fixed..
So basically i think there should be no code in the .aspx page as i have to create the gridview in codebehind.
I have the code for 1 gridview in one panel.. where i define the grid view in the HTML page and populate it from the code behind.
Here is the code for that.. can any 1 please help me with the multiple gridviews...
this is on the .aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AllowSorting="True" CellSpacing="2" onsorting="GridView1_Sorting"
Width="100%" ForeColor="White" GridLines="None"
ondatabound="GridView1_DataBound1">
<Columns>
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("PolicyID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("PolicyID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
this is the code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(Session["ConnectionStringSQL"].ToString());
connection.Open();
SqlCommand sqlCmd = new SqlCommand("SELECT Policies.PolicyID, FROM Policies", connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
connection.Close();
if (dt.Rows.Count > 0)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
policyID.Add(dt.Rows[j]["PolicyID"].ToString());
}
taskTable.Columns.Add("PolicyID");
if (policyID.Count != 0)
{
for (int k = 0; k < policyID.Count; k++)
{
DataRow tableRow = taskTable.NewRow();
tableRow["PolicyID"] = policyID[k];
taskTable.Rows.Add(tableRow);
}
Session["TaskTable"] = taskTable;
GridView1.DataSource = Session["TaskTable"];
GridView1.DataBind();
}
}
}
}
Answer 1 works but just be careful if you are nesting this inside a master page, etc.. because it seems when you just bind directly to the PAGE you cant expect it to actually be placed inside your form tag.
I have a sproc that returns unknown number of different tables that i want dumped to the page so i put a Placeholder on the aspx page
and then used the loop thru my dataset
foreach (DataTable table in ds.Tables)
{
GridView gv = new GridView();
gv.DataSource = table;
gvPlaceHolder.Controls.Add(gv);
}
.....OR ....
for (int i = 0; i < ds.Tables.Count; i++)
{
GridView gv = new GridView();
gv.DataSource = ds.Tables[i];
gvPlaceHolder.Controls.Add(gv);
}
.. and then bind to the placeholder so the tables end up inside my form within my child page, that is inside my master page
gvPlaceHolder.DataBind();
Not tested, but this kind of thing should do it:
for (int i=0;i<5;i++) {
GridView gv = new GridView();
gv.DataSource = datasources[i];
Page.Controls.Add(gv);
}
Page.DataBind();
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);
}
}