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);
}
}
Related
Please find image. Here's my whole code, I wanted save each row on save button click. I'm able to get value from cell 0 and cell 1 but unable to get value from cell 2 , where I have drop down list selected value.I'm getting default value "Ignore" instead of selected item. So how do I get selected value of drop down list ?
<div>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns = "False"
OnRowDataBound = "OnRowDataBound" Width="544px">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:TemplateField HeaderText = "Mapping" >
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" style="font-size: medium; font-family: Cambria" Width="300px">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button2" runat="server" Text="Save"
style="font-size: medium; font-family: Cambria" BorderStyle="Groove"
height="32px" Width="116px" onclick="Save_Click" />
</div>
private void BindGrid()
{
DataTable dt = new DataTable();
connection();
cmd = new SqlCommand("Select top 0 * from F3_BC_Product_Mapping_Data", con);
con.Open();
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds, "mytable");
int j = 1;
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)) });
foreach (DataColumn column in ds.Tables[0].Columns)
{
dt.Rows.Add(j,column.ColumnName);
j++;
}
GridView2.DataSource = dt;
GridView2.DataBind();
con.Close();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlMap = (e.Row.FindControl("DropDownList1") as DropDownList);
DataTable dt = new DataTable();
dt = (DataTable)Session["data"];
for (int i = 0; i < dt.Columns.Count; i++)
{
ddlMap.Items.Add(dt.Columns[i].Caption.ToString());
}
ddlMap.Items.Insert(0, new ListItem("Ignore"));
}
}
protected void Save_Click(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView2.Rows)
{
string cell_1_Value = GridView2.Rows[gr.RowIndex].Cells[0].Text;
string cell_2_Value = GridView2.Rows[gr.RowIndex].Cells[1].Text;
string cell_3_Value = ((DropDownList)gr.FindControl("DropDownList1")).SelectedItem.Value;
}
}
If you are getting default value then you must see binding code. I think you haven't use if(!Page.IsPostBack) before binding and setting default value in drop down. Try to change OnRowDataBound as below.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && !Page.IsPostBack)
{
DropDownList ddlMap = (e.Row.FindControl("DropDownList1") as DropDownList);
DataTable dt = new DataTable();
dt = (DataTable)Session["data"];
for (int i = 0; i < dt.Columns.Count; i++)
{
ddlMap.Items.Add(dt.Columns[i].Caption.ToString());
}
ddlMap.Items.Insert(0, new ListItem("Ignore"));
}
}
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 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
I've searched and searched, and I think this should be rather straight forward, but I can't figure it out. I have a DataSet (myDataSet) to which I have added several tables (myDataTable). I also have a GridView. I want to set the GridView up so that each page on the GridView is bound to each each table of the DataSet (i.e. page 1 of GridView = DataSet.Table[0], etc.). The tables all have the same columns, but differing number of rows.
With PageSize = number of rows in the table, the buttons disappear completely even though I have explicitly set PageButtonCount to 3 (there are 3 tables in this dataset). I suppose there's some sort of automagical paging feature that's determining that no more pages are needed but I can't sort out how to make it work.
public partial class _Default : System.Web.UI.Page
{
Users theUsers = new Users();
static DataSet myDataSet = new DataSet();
DataTable myDataTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
protected bool runReport()
{
ltError.Visible = false;
try
{
using (MySqlConnection dbConn = new MySqlConnection(ConfigurationManager.ConnectionStrings["AsteriskConn"].ConnectionString))
{
//sql query
string sql = "SELECT calldate, src, dst, duration FROM cdr WHERE (src LIKE #ext AND dst > 9999)" +
"OR (dst LIKE #ext AND src > 9999) AND dst NOT LIKE '*%'";
MySqlDataAdapter adapter = new MySqlDataAdapter();
dbConn.Open();
myDataSet.Tables.Clear();
int j = ddlUsers.SelectedIndex;
//loop through each user in the list and query the database for its cdr records with the sql query string
foreach (int i in theUsers.groups[j].extensions)
{
myDataTable = new DataTable();
adapter.SelectCommand = new MySqlCommand(sql, dbConn);
adapter.SelectCommand.Parameters.Add("#ext", MySqlDbType.VarChar, 80).Value = i;
adapter.Fill(myDataTable);
myDataTable.TableName = i.ToString();
myDataSet.Tables.Add(myDataTable);
}
gvReport.DataSource = myDataSet;
gvReport.AllowPaging = true;
gvReport.PageSize = myDataSet.Tables[0].Rows.Count;
gvReport.PagerSettings.PageButtonCount = myDataSet.Tables.Count;
gvReport.PagerSettings.Mode = PagerButtons.NumericFirstLast;
gvReport.PagerSettings.Position = PagerPosition.Top;
gvReport.PagerSettings.Visible = true;
gvReport.DataBind();
dbConn.Close();
}
}
}
}
protected void gvReport_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvReport.PageIndex = e.NewPageIndex;
gvReport.DataSource = myDataSet.Tables[e.NewPageIndex];
gvReport.DataBind();
}
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Panel ID="Panel1" runat="server" HorizontalAlign="Center">
<asp:GridView ID="gvReport" runat="server" OnPageIndexChanging="gvReport_PageIndexChanging"
onrowdatabound="gvReport_RowDataBound" Visible="False" HorizontalAlign="Center" AllowPaging="true">
<PagerSettings Position="Top" />
</asp:GridView>
<asp:Literal ID="ltError" runat="server" Visible="False"></asp:Literal>
</asp:Panel>
</asp:Content>
i think, you better add the page index buttons/link buttons, dynamically (or use repeater to show the page index buttons)
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.