How add control programmatically in gridview template? - c#

I want add control label in my gridview, is it possible add with datatable?
here my code:
<asp:GridView ID="reportScheduleDetailsGridView"
runat="server"
AutoGenerateColumns="False">
</asp:GridView>
I try use tag html span, but it not render:
string queryString = #"SELECT * FROM [table1]";
SqlCommand cmd = new SqlCommand(queryString, connOkto);
using (SqlDataReader sdrMaster = cmd.ExecuteReader())
{
while (sdrMaster.Read())
{
DataRow rows = dataTable.NewRow();
rows[0] = sdrMaster["name"].ToString();
for (var x = 1; x < maxCol; x++)
{
queryString = #"SELECT * FROM table2";
cmd = new SqlCommand(queryString, connOkto);
using (SqlDataReader sdrRev = cmd.ExecuteReader())
{
while (sdrRev.Read())
{
blok = "<span></span>";
no = (int)Int16.Parse(sdrRev["no"].ToString());
}
}
rows[x] = blok;
if (no > 1)
{
no--;
}
else
{
blok = "";
}
}
dataTable.Rows.Add(rows);
} }
I don't know, how can add control asp in gridview, like label.
Please help, thanks.

One way to add controls is using OnRowDataBound event of GridView. Add a placeHolder to say, inside <ItemTemplate> of your grid view.
<asp:GridView ID="EmpGridView" OnRowDataBound="EmpGridView_RowDataBound"
<ItemTemplate>
<asp:PlaceHolder ID="placeholder1" runat="server"></asp:PlaceHolder>
</ItemTemplate>
...></asp:GridView>
Ang your code behind file will have:
protected void EmpGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Create a label control
Label lbl = new Label();
lbl.Text="MyDynamic Label";
lbl.ID="lbl1"; // use ID values you prefer
// lets create one more control for example
LinkButton btnlink = new LinkButton();
btnlink.Text = "Delete";
btnlink.ID = "btnDelete";
linkb.Click += new EventHandler(btnlink_Click);
// add the controls to your placeholder inside <ItemTemplate>
PlaceHolder phld = e.Row.FindControl("Placeholder1") as PlaceHolder;
phld.Controls.Add(btnlink);
phld.Controls.Add(lbl);
//code to add the control to only a specific COLUMN/ Cell
e.Row.Cells[1].Controls.Add(btnlink); // adding to 2nd Column
// adding to last column..
e.Row.Cells[EmpGridView.Columns.Count - 1].Controls.Add(btnlink);
}
}
Hope this various ways of adding controls to Templates as well as in a cell of GridView helps you.

Related

Display DropDownlist when click on specific cell asp.net table

I am trying to figure it out how can I display a dropDownList on a specific cell in the table right after clicking a button "Show DropDownlist" located on that cell.
This is the behind code , right now it is displaying the dropDownList at the last cell of each row. and I want to make it appear only when a button is clicked.
while (rdr.Read())
{
TableRow tRow = new TableRow();
myTable.Rows.Add(tRow);
for (int i = 0; i <= 4; i++)
{
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
if (i == 4)
{
tCell.Controls.Add(SM_List()); //Adding the dropdownlist
tRow.Cells.Add(tCell);
continue;
}
tCell.Text = rdr.GetString(i);
tCell.Attributes.Add("onmouseover", "this.style.cursor = 'pointer'; this.style.backgroundImage = ''; ");
tCell.Attributes.Add("onClick", "getData()");
tRow.Cells.Add(tCell);
}
/* iterate once per row */
}
I want to add this code, so it will be a button at first , instead of a drop down list :
Button bt = new Button();
bt.Text = "Switch";
bt.Click += new EventHandler(DropDownList_Show);
tCell.Controls.Add(bt);
But I am not sure how to display the DropDownList at the exact cell the button was located. and also I want to do some actions when Value was selected in the dropdownlist.
Can you please assist , I feel a little bit lost.
You can solve this issue easily by using GridView in ASP.NET.
Let say the GridView is declared as following in ASPX page.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" />
<asp:BoundField DataField="Token" />
<asp:BoundField DataField="Secret" />
<asp:ButtonField CommandName="ShowDropDown" Text="Show" />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="dropDownList" runat="server" Visible="false">
<asp:ListItem Text="Valid" Value ="1"></asp:ListItem>
<asp:ListItem Text="Invalie" Value ="2"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Following is the method in code behind which populates the GridView.
private void BindGridView()
{
var tokens = new List<AccessToken>();
using (var conn = new SqlConnection("Server=somedbserver;Database=somedatabase;User Id=someuser;Password=somepassword;"))
{
using (var command = new SqlCommand())
{
command.Connection = conn;
command.CommandText = "SELECT Id, Token, Secret FROM Tokens";
command.CommandType = System.Data.CommandType.Text;
conn.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var token = new AccessToken();
token.Id = reader.GetInt32(0);
token.Token = reader.GetString(1);
token.Secret = reader.GetString(2);
tokens.Add(token);
}
}
}
}
GridView1.DataSource = tokens;
GridView1.DataBind();
}
And I am calling this method in Page_Load.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridView();
}
}
Following is the event handler of RowCommand event of GridView which will display the dropdown list in the column next to the button which is clicked.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "ShowDropDown")
{
var row = GridView1.Rows[Convert.ToInt32(e.CommandArgument)];
//Using Cell[4] coz the Dropdownlist is in 5th column of the row.
//You need to replace 4 with appropriate column index here.
//Also replace "dropDownList" with the ID assigned to the dropdown list in ASPX.
var ddl = (DropDownList)row.Cells[4].FindControl("dropDownList");
if(ddl != null)
{
ddl.Visible = true;
}
}
}
You will able resolve your issue if you follow this approach.

Formatting Cells on Gridview from SQL Data Reader

I have a Grid view which populates through my SQL data reader
Grid View:
<asp:GridView ID="gridviewALL" runat="server" OnItemDataBound="Search_ItemDataBound">
</asp:GridView>
SQL Data Reader:
SqlCommand cmd = new SqlCommand("SELECT en.dpCreatedDT AS 'Time Received', en.enStatusCH AS 'Status', en.enNotificationNoNI AS 'LSBUD Ref', cm.cmpersonfirstch AS 'First Name', cm.cmPersonLastCH AS 'Last Name', cm.cmcompanynamech AS 'Company' FROM dp_enquiry en JOIN dp_caller_master cm ON (en.encmcallerkeyfk = cm.cmCallerKeyNI) WHERE en.ennotificationnoni = #JobnoALL", conn);
try
{
SqlParameter search = new SqlParameter();
search.ParameterName = "#JobnoALL";
search.Value = JobnoALL.Text.Trim();
cmd.Parameters.Add(search);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
gridviewALL.DataSource = dt;
gridviewALL.DataBind();
}
I'm trying to change the format of a cell in the grid view when the text equals a value, I've done this using a listview before but the Gridview steps seems different. I have the following which doesn't seem to be working any suggestions?
private void Search_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
string CurrentColumn = e.Item.Cells[1].Text;
if (CurrentColumn == "PROC")
{
e.Item.Cells[1].Text = "Creating PDF";
}
else if (CurrentColumn == "CLOS")
{
e.Item.Cells[1].Text = "Complete";
e.Item.Cells[1].ForeColor = System.Drawing.Color.Green;
}
}
It must be reading the header, you need to check if its a DataRow:-
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CurrentColumn = e.Item.Cells[1].Text;
//your code goes here..
}
Also, I would suggest you to use DataBinder.Eval method instead to avoid hard-coding of cell index as it may result in error if order of columns change.
string CurrentColumn = DataBinder.Eval(e.Row.DataItem, "yourColumnName").ToString();
Update:
Just noticied you are using ItemDataBound which is an event for DataGrid and not Gridview. Use RowDataBound event instead:-
<asp:GridView ID="gridviewALL" runat="server" OnRowDataBound="gridviewALL_RowDataBound">
</asp:GridView>
Your rowDataBound event should look like this:-
protected void gridviewALL_RowDataBound(object sender, GridViewRowEventArgs e)
{
//your code here
}

Delete Selected Dynamic Checkboxes on Gridview ASP.NET

I have a gridview that contains data from a database. I have dynamically created checkboxes for each row. What I want is when I click the "delete selected" button, the checkboxes that are checked will be deleted. But the rows don't get deleted when I click the button. Here is the code for the button:
protected void btnDeleteSelectedServiceProvidersLocations_Click(object sender, EventArgs e)
{
int x = 102;
string delete;
foreach (GridViewRow grow in gvServiceProviders.Rows)
{
delete = Request.Form["gvServiceProviders$ct" + x + "$cbSelect"];
if (delete != null || delete == "on" || delete == "y")
{
bll.ServiceProviderLocationID = grow.Cells[1].Text;
bll.IsDeleted = "y";
bll.ServiceProviderLocationDelete();
}
x++;
}
gvServiceProviders.DataSource = bll.GetServiceProviderLocations();
gvServiceProviders.DataBind();
}
The gridview is inside an update panel, if that helps. And I'm using a three-tier approach.
ASPX code:
<div ID="gridView">
<asp:GridView ID="gvServiceProviders" runat="server">
<Columns>
<asp:templatefield HeaderText="Select">
<itemtemplate>
<asp:CheckBox ID="cbSelect" runat="server"/>
</itemtemplate>
</asp:templatefield>
</Columns>
</asp:GridView>
</div>
You want to delete the data when the check box is selected then you can do as below,
foreach (GridViewRow grow in gvServiceProviders.Rows)
{
//Make sure it is datarow
if(grow.RowType = RowType.DataControlRowType.DataRow)
{
//Finiding checkbox control in gridview for particular row
CheckBox chkdelete = (CheckBox)grow.FindControl("cbSelect");
//Make sure if checkbox is selected for the processing row
if(chkdelete.Checked)
{
//Getting your datakey value
bll.ServiceProviderLocationID = Convert.ToInt32(gvServiceProviders.DataKeys[grow.RowIndex].Value);
bll.IsDeleted = "y";
bll.ServiceProviderLocationDelete();
}
}
}
gvServiceProviders.DataSource = bll.GetServiceProviderLocations();
gvServiceProviders.DataBind();
As this is using the datakey of the gridview you need to set the DataKey property of the gridview with the LocationID.
Try this code:
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in gvDetails.Rows)
{
//Finiding checkbox control in gridview for particular row
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkSelect");
//Condition to check checkbox selected or not
if (chkdelete.Checked)
{
//Getting UserId of particular row using datakey value
int usrid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value);
using (SqlConnection con = new SqlConnection("Data Source=Test;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("delete from UserDetails where UserId=" + usrid, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}

From Page_Load to One_Method and from One_Method to Another_Method

Hey I make one more question with my full code because I am really stuck in this point.
When page loads a panel is filled with Book Categories taken from a database. This Categories are linkbuttons too. When I click one category a table is created below with all books on that category.
In that table the first cell is filled with Book's Title that is Linkbutton too.
I just want when I click i that Book'S Title linkbutton to fire the book_Details functions
so that the page now will show only the book I chose.
Instead of that whenever I click books'title linkbutton page loads again from 0.
The markup is:
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<div style="position: relative; top: 5%; left: 5%;">
<asp:Panel ID="MyPanel" runat="server"></asp:Panel>
</div>
<asp:MultiView ID="MultiView2" runat="server">
<asp:View ID="View1" runat="server">
<div style="overflow: auto; height: 400px;">
<asp:Table ID="ProductTBL" runat="server" BorderColor="Black" BorderStyle="Double" CellPadding="5" CellSpacing="5" BorderWidth="1px">
</asp:Table>
</div>
</asp:View>
<asp:View ID="View2" runat="server">
<asp:Table ID="detail_TBL" runat="server" BorderColor="Black" BorderStyle="Double" CellPadding="5" CellSpacing="5" BorderWidth="1px"></asp:Table>
</asp:View>
</asp:MultiView>
</asp:Content>
And the code-behind is:
protected void Page_Load(object sender, EventArgs e)
{
String conString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" +
Server.MapPath("~/e-bookstoredb.accdb");
using (OleDbConnection connection = new OleDbConnection(conString))
{
connection.Open();
ыtring query = "SELECT * FROM category";
using (OleDbCommand cmd = new OleDbCommand(query, connection))
{
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string literal = (string)reader["Name"];
LinkButton lnk_button = new LinkButton();
lnk_button.Text = literal;
lnk_button.ID = "cat_B" + reader["ID"].ToString();
lnk_button.CommandArgument = reader["ID"].ToString();
lnk_button.CommandName = reader["ID"].ToString();
lnk_button.Command += new CommandEventHandler(books_Show);
MyPanel.Controls.Add(lnk_button);
MyPanel.Controls.Add(new LiteralControl("</br>"));
}
reader.Close();
}
connection.Close();
}
}
protected void books_Show(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
string cat = lnk.CommandArgument;
MultiView2.ActiveViewIndex = 0;
string ConStr = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" + Server.MapPath("~/e-bookstoredb.accdb");
using (OleDbConnection con = new OleDbConnection(ConStr))
{
con.Open();
string query = "SELECT * FROM product WHERE category = #cat";
using (OleDbCommand cmd = new OleDbCommand(query, con))
{
cmd.Parameters.AddWithValue("#cat", cat);
OleDbDataReader reader = cmd.ExecuteReader();
TableCell cell;
TableRow row = new TableRow();
TableCell titleCell = new TableCell();
titleCell.Text = "Τίτλος";
TableCell desCell = new TableCell();
desCell.Text = "Περιγραφή";
TableCell priceCell = new TableCell();
priceCell.Text = "Τιμή";
row.Cells.Add(titleCell);
row.Cells.Add(desCell);
row.Cells.Add(priceCell);
ProductTBL.Rows.Add(row);
LinkButton book_button;
while (reader.Read())
{
book_button = new LinkButton();
book_button.ID = "book" + reader["ID"].ToString();
book_button.Text = (string)reader["Title"];
book_button.CommandArgument = (string) reader["Title"];
book_button.CommandName = "cmd" + reader["ID"].ToString();
book_button.Command += new CommandEventHandler(book_Details);
row = new TableRow();
cell = new TableCell();
cell.Controls.Add(book_button);
row.Cells.Add(cell);
cell = new TableCell();
cell.Text = (string)reader["Description"];
row.Cells.Add(cell);
cell = new TableCell();
cell.Text = reader["price"].ToString()+"€";
row.Cells.Add(cell);
ProductTBL.Rows.Add(row);
}
reader.Close();
}
con.Close();
}
}
protected void book_Details(object sender, EventArgs e)
{
MultiView2.ActiveViewIndex = 1;
LinkButton lnk = sender as LinkButton;
String bookTitle = lnk.CommandArgument;
//...And then I just create a table to show only the book user selected
//...this table gets filled buy this query = " SELECT * FROM product WHERE Title=#bookTitle
}
You must wrap your code within Page_Load with if(!IsPostBack) as shown below. This is because according to ASP.Net page lifecycle Page_Load fires first and control events firs after that.
So, whenever you click your LinkButtons the server first calls the Page_Load and then it calls LinkButton's click event.
So, it's a good idea to wrap your Page_Load code where you only wants to execute once during Page_Load like this.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Your Page_Load logic goes here
}
}
According to MSDN the definition for IsPostBack is
Gets a value that indicates whether the page is being rendered for the
first time or is being loaded in response to a postback.
true if the page is being loaded in response to a client postback;
otherwise, false.
Hope this helped!

Dynamic Controls in PlaceHolder were lost after an action is performed

I have a PlaceHolder in a webform with Master page with the code
<asp:DropDownList ID="NoofSubjectList" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="NoofSubject_Index_Changed">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
</asp:DropDownList>
<asp:PlaceHolder ID="placeholder" runat="server" />
Based on the number(n) selected from the DropDownList (1), I will be Dynamically creating two sets of DropDownList (2,3) for the selected n numbers. In that the first DropDownList loads data from a database. The code is shown below,
protected void NoofSubject_Index_Changed(Object sender, EventArgs e)
{
int value = Convert.ToInt32(NoofSubjectList.SelectedItem.Text.ToString());
DataSet ds1 = new DataSet();
MySql.Data.MySqlClient.MySqlConnection mysqlConnection = new
MySql.Data.MySqlClient.MySqlConnection
("Database=school;Server=localhost;UID=root;PWD=;");
MySql.Data.MySqlClient.MySqlCommand mysqlCommand = new
MySql.Data.MySqlClient.MySqlCommand
("SELECT Dept FROM tabledept WHERE Status='Active'", mysqlConnection);
MySql.Data.MySqlClient.MySqlDataAdapter mysqlAdaptor = new
MySql.Data.MySqlClient.MySqlDataAdapter(mysqlCommand);
mysqlAdaptor.Fill(ds1);
for (int i = 0; i <= value - 1; i++)
{
DropDownList _SubList = new DropDownList();
_SubList.ID = "SubList" + (i + 1);
_SubList.Width= 75;
DropDownList _DeptList = new DropDownList();
_DeptList.ID = "DeptList" + (i + 1);
_DeptList.Width = 75;
_DeptList.SelectedIndexChanged += DeptList_Index_Changed;
Literal _spacer = new Literal();
_spacer.Text = "<br />";
Literal _spacerlbl = new Literal();
_spacerlbl.Text = " ";
Label _Lbl = new Label();
_Lbl.ID = "lbl_Subject" + i;
_Lbl.Text = "Subject" + (i+1);
Label _Lbl1 = new Label();
_Lbl1.ID = "lbl_Dept" + i;
_Lbl1.Text = "Department";
_DeptList.DataSource = ds1;
_DeptList.DataTextField = ds1.Tables[0].Columns["Dept"].ColumnName;
_DeptList.DataValueField = ds1.Tables[0].Columns["Dept"].ColumnName;
_DeptList.DataBind();
_DeptList.AutoPostBack = true;
placeholder.Controls.Add(_Lbl1);
placeholder.Controls.Add(_spacerlbl);
placeholder.Controls.Add(_DeptList);
placeholder.Controls.Add(_spacerlbl);
placeholder.Controls.Add(_Lbl);
placeholder.Controls.Add(_SubList);
placeholder.Controls.Add(_spacer);
}
}
protected void DeptList_Index_Changed(Object sender, EventArgs e)
{
\\Based on the selection in DropDownList2, a list will be loaded from a
\\database to DropDownList3
}
The above event is triggered based on the selection of the number n from the DropDownList (1). If I select an item from DropDownList (2) the data will be generated from database and added to the DropDownList (3) . The problem is when I try to select an item from DropDownList (2), the dynamically created controls get lost. How to overcome this issue?
I even googled it and I found out that I am missing something called PostBack in my code. But I could not able to find out relevant resource to learn about it
I got a link which shows an easy example of creating the controls after postback.
Creating Dynamic TextBox Controls using C#

Categories

Resources