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.
Related
It is something very simple but i am stuck on this for ages.
So i had created a datatable and got the data onto a gridview. Great
Made the Sheet_id clickable and when clicking it i will direct to a new page.
However i want to get the sheet_id which i selected from the gridview in order to use it for other sql query.
How do i pass that sheet_id from one page to another page using the linkbutton.
This is ExistingSheet.aspx
<asp:GridView ID="grdSheet" runat="server" AutoGenerateColumns="False"
CssClass="tablesorter table table-bordered table-hover table-striped tblCtr"
>
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Label ID="hdnSheetId" runat="server" Text='<%# Eval("SNO")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sheet ID">
<ItemTemplate>
<asp:LinkButton runat="server" ID="sheetId" CommandName="sheet_id" CommandArgument='<%# Eval( "sheet_id")%>' Text='<%# Eval( "sheet_id")%>' OnClick="" PostBackUrl="~/SheetDetail.aspx">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
This is ExistingSheet.aspx.cs
protected void grdSheet_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Redirect("SheetDetail.aspx" + e.CommandArgument);
}
This is the page i wanted to get the data to SheetDetail.aspx.cs
public void FillGridSheet()
{
eExistingSheetQuery existingSheetQuery = new eExistingSheetQuery();
grdSheetDetail.DataSource = existingSheetQuery.DisplayReportSheet(**SHEET ID TO BE PLACED HERE**);
grdSheetDetail.DataBind();
}
This is eExistingSheetQuery.cs
public DataTable DisplayReportSheet(string sheetId)
{
try
{
conn = new SqlConnection(estocktake);
conn.Open();
DataTable dtd = new DataTable();
GridView gvd = new GridView();
cmds = new SqlCommand("Select ROW_NUMBER( ) OVER (order by sheet_id) as SNO, csd.Barcode, csd.ItemId, pm.Description, csd.Quantity " +
"from CountSheetDetails csd " +
"join ProductMaster pm on pm.Barcode = csd.Barcode and pm.ItemId = csd.ItemId " +
"where csd.SheetId = '" + sheetId + "' and pm.Status ='A';",conn);
adpt = new SqlDataAdapter();
adpt.SelectCommand = cmds;
cmds.ExecuteNonQuery();
adpt.Fill(dtd);
conn.Close();
conn.Dispose();
for (int i = 0; i < dtd.Rows.Count; i++)
{
dtd.Rows[i]["SNO"] = i + 1;
}
return dtd;
}
catch (Exception)
{
conn.Close();
conn.Dispose();
return null;
}
}
i wanted to use the id to beable to use it for the next query that i am going to pull from SQL
I had seen a few example but i do not think i really understand. Any suggestion will be great. thanks!
I think what you're asking is a way to pass data from one GridView to another, but on a different page?
Using a loop mechanism, I suggest you loop through your source Gridview and copy them into your destination GridView. Get this to work first on a single page first - ie GridView to GridView.
For example, you'll need a trigger. Here's a Button trigger to get the data ...
GridView1 = your source GridView
GridView2 = your destination GridView
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("ColumnName1"));
dt.Columns.Add(new DataColumn("ColumnName2"));
dt.Columns.Add(new DataColumn("ColumnName3"));
foreach (GridViewRow gvr in GridView1.Rows)
{
if (((CheckBox)gvr.Cells[4].FindControl("CheckBox")).Checked == true)
{
dr = dt.NewRow();
dr["ColumnName1"] = ((Label)gvr.Cells[0].FindControl("Label")).Text;
dr["ColumnName2"] = ((Label)gvr.Cells[1].FindControl("Label")).Text;
dr["ColumnName3"] = ((Label)gvr.Cells[2].FindControl("Label")).Text;
dt.Rows.Add(dr);
}
}
foreach (GridViewRow gvr in GridView2.Rows)
{
dr = dt.NewRow();
dr["ColumnName1"] = ((Label)gvr.Cells[0].FindControl("Label")).Text;
dr["ColumnName2"] = ((Label)gvr.Cells[1].FindControl("Label")).Text;
dr["ColumnName3"] = ((Label)gvr.Cells[2].FindControl("Label")).Text;
dt.Rows.Add(dr);
}
GridView2.DataSource = dt;
GridView2.DataBind();
}
Once you get this to work, your way, then we figure out how to pass the data across different web URLs.
One approach is to use SessionState[]. Here.
The concept is basically about passing data into memory, which is the SessionState or ViewState, and then retrieving that data from the receiving page via it's PageLoad() event. OR you save the data into a temporary table, and reload it again onto the new page, using standard DataSource attributes.
Examples here and here.
I have a GridView that I populate. It appears correctly and shows the data. It contains a Checkbox column, and my intent is when the user clicks a button on the form, it iterates through the rows of the GridView, and totals up all the rows the user has selected by checking the CheckBox.
(I got the details of how to do this from http://asp.net-informations.com/gridview/checkbox.htm)
The problem comes at this point, and I've discovered that just before it gets to the line
foreach (GridViewRow row in grdItems.Rows)
grdItems.Rows.Count = 0, even though the GridView is currently displaying data.
The GridView:
<asp:GridView ID="grdItems" AutoGenerateColumns="false" runat="server" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkCtrl" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Item_No" HeaderText="Item No" />
<asp:BoundField DataField="Amount" HeaderText="Amount" />
</Columns>
</asp:GridView>
The Button:
<asp:Button ID="cmdOK" runat="server" Text="Add" />
The Button Onclick:
protected void cmdOK_Click(object sender, EventArgs e)
{
if (ValidateForm())
{
SaveP2P();
}
}
The method the populates the GridView:
private void FillGrid()
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Snipped for privacy");
conn.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandText = "Snipped for privacy";
cmd.Connection = conn;
System.Data.OleDb.OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter(cmd);
System.Data.DataSet ds = new System.Data.DataSet();
adp.Fill(ds);
adp.Dispose();
cmd.Dispose();
conn.Close();
grdItems.DataSource = ds;
grdItems.DataBind();
}
The ValidateForm() method which contains the code I'm struggling with
private bool ValidateForm()
{
bool result = true;
decimal TotalAmount = 0;
//If I display a message here, it shows grdItems.Rows.Count is 0
foreach (GridViewRow row in grdItems.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
TotalAmount += Decimal.Parse(row.Cells[2].Text);
}
}
}
decimal amount;
if (decimal.TryParse(txtAmount.Text, out amount))
{
if (amount > TotalAmount)
{
result = false;
}
}
else
{
result = false;
}
return result;
}
This sounds like a viewstate issue where when the page is posting back to the server, it is losing all the data in the grid. Have you tried enabling viewstate on your page to see if the gridview rows are returned.
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();
}
}
}
I have a gridview that is populated with data from SQL and I would like to add buttons/linkbuttons dynamically to its columns.
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
Button button = new Button();
button.ID = "row" + e.Row.RowIndex;
button.Text = "click me";
button.Click += new EventHandler(Unnamed_Click);
e.Row.Cells[1].Controls.Add(button);
}
Visually that works fine but when clicking it, it does a postback and the changes are lost. The buttons are gone.
Where can I recreate them so they persist?
You can use command field or template field for buttons,
below is example for image button:
<asp:CommandField ShowEditButton="true" EditImageUrl="~/images/edit.png" ButtonType="Image" ItemStyle-Width="20px" HeaderStyle-Width="20px" AccessibleHeaderText="Edit">
<HeaderStyle Width="20px" />
<ItemStyle Width="20px" />
</asp:CommandField>
Or
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" CommandName="Edit"
ImageUrl="~/images/edit.png" ToolTip="Click to Edit></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
Please use the below steps to bypass the binding of grid in case the click me button was clicked
Change your OnRowBound function code to:
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItemIndex != -1)
{
Button button = new Button();
button.ID = "gridview1row" + e.Row.RowIndex;
button.UseSubmitBehavior = false;
button.Text = "click me";
button.Click += new EventHandler(Unnamed_Click);
e.Row.Cells[1].Controls.Add(button);
}
}
Add the below check to you Page_Load before Grid View Load
protected void Page_Load(object sender, EventArgs e)
{
try
{
if ( Request.Params["__EventTarget"] == null || !Request.Params["__EventTarget"].Contains("gridview1row"))
{
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
using (SqlCommand command =
new SqlCommand("SELECT TOP 100 * FROM dbo.TableName", connection))
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = command;
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
}
catch (Exception ex)
{
}
}
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.