I'm trying to do a project for car maintenance, and I have a small problem. The project is something like:
4 kind of maintenance plans for different cars.
CarA ( MirrorA, etc etc )
CarB ( MirrorB, etc etc )
CarC ( MirrorC, etc etc )
CarD ( MirrorD, etc etc )
What I'm trying to do is when I chose a Car (from a DropDownList), the program selects the right maintenance plan for the car!
SqlCommand cmd = new SqlCommand("Select id, description from accauto_maps", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "description";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
Now I'm stuck.
now you need to set SelectedValue in this list
and/or
define event OnSelectedIndexChanged where you will process user's selection
Below the example how we did it:
<asp:DropDownList ID="ddlStatus" AutoPostBack="True" runat="server" DataSourceID="EDSLookStatus"
DataValueField="cd"
DataTextField="lookupName"
OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged" />
<asp:TextBox ID="txtBxStatus" runat="server" Text='<%# Bind("status") %>' Visible="False" />
Here is the trick: added invisible textbox, which is linked to "status". When ddl change value it set new value to this txtBx:
protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = FormViewClient.FindControl("ddlStatus") as DropDownList;
TextBox txtBx = FormViewClient.FindControl("txtBxStatus") as TextBox;
if (ddl != null && txtBx != null)
{ txtBx.Text = ddl.SelectedValue; }
}
to set selected value:
<asp:FormView ... OnDataBound="FormViewClient_DataBound" >
and
protected void FormViewClient_DataBound(object sender, EventArgs e)
{
...
DropDownList ddl = FormViewClient.FindControl("ddlStatus") as DropDownList;
TextBox txtBx = FormViewClient.FindControl("txtBxStatus") as TextBox;
if (ddl != null && txtBx != null)
{ ddl.SelectedValue = txtBx.Text; }
...
}
Related
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.
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 repeater that retrieve data from my db.
some of the results are getting a null value in a specific column due to
a join query and its fine.
I would like to go over each row and if the result is null for the specific
row i want to change the css for this row.
Now for the code:
<asp:Repeater ID="repRequests" OnItemDataBound="repRequests_ItemDataBound" runat="server">
<ItemTemplate>
<asp:Label ID="lbltest" runat="server" Text='<%#Eval("val_name") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
C#:
if (!IsPostBack)
{
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("check_accepted", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#val_name", Session["valName"].ToString());
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
repRequests.DataSource = dr;
repRequests.DataBind();
}
}
How to write this ?
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
**//what i want to get:**
if (dr["accepted_id"] == Null) // a column from the db table
{
repRequests.attribute["class"] = "Some Class"
}
}
}
Thanks for the helpers !
You can try the following. If the data source is a DataReader object, you must cast e.Item.DataItem as type DBDataRecord (from System.Data.Common)
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Data.Common.DbDataRecord dataRow = e.Item.DataItem as System.Data.Common.DbDataRecord;
if (dataRow["accepted_id"] == DBNull.Value || dataRow["accepted_id"] == null) // a column from the db table
{
// I am not sure how to you get repRequests. but you can find the control using e.Row.Item.FindControl() function
repRequests.attribute["class"] = "Some Class";
}
}
}
EDIT
Further to your questions, if you want to change the css of a perticular row, if some value is null, you cannot set css to repeater or repeater item directly. What you need to do is add a top level panel to the ItemTemplate like this
<ItemTemplate>
<asp:Panel runat="server" ID="panelRow">
<asp:Label ID="lbltest" runat="server" Text='<%#Eval("val_name") %>'></asp:Label>
</asp:Panel>
</ItemTemplate>
Then you can change the css of the panel like below
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Data.Common.DbDataRecord dataRow = e.Item.DataItem as System.Data.Common.DbDataRecord;
if (dataRow["accepted_id"] == DBNull.Value || dataRow["accepted_id"] == null) // a column from the db table
{
Panel panelRow = e.Item.FindControl("panelRow") as Panel;
panelRow.CssClass = "yourcssclass";
}
}
}
If not, you can use IsNull in your query.
SqlCommand cmd = new SqlCommand("select IsNull(something,zero) from sometable",connectionstring)
SqlDatareader dr = cmd.ExecuteReader();
while(dr.Read())
{
if(dr.GetString(0)=="zero")
{
repRequests.attribute["class"] = "Some Class";
}
}
Here is link example of DbDataRecord when you bind repeater control with sqldatareader.
Also note that repRequests.attribute["class"] = "Some Class" this means you are applying CSS Class to the repeater control. You need to change the CssClass label which is used as item of repeater control.
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
DbDataRecord dbr = (DbDataRecord)e.Item.DataItem;
if( Convert.ToString(DataBinder.Eval(dbr, "accepted_id")) == null )
((Label)e.Item.FindControl("lbltest")).CssClass = "Some Class";
}
}
Good day, I want the text of the button inside the repeater to change dynamically based on what the sql selected values would have.
here's my code:
asp.cs
if (!IsPostBack)
{
string getEmp = "Select employeeid, photo, lastname, firstname, departmentname, designation,userType from tblEmployee e inner join tblDepartment d on d.departmentid=e.department";
SqlCommand com = new SqlCommand(getEmp,con);
con.Open();
SqlDataReader dr = com.ExecuteReader();
Button btnSet = (Button)FindControl("btnSet");
if (dr.HasRows)
{
if (dr.Read())
{
if (btnSet != null)
{
if (dr["userType"].ToString() == "2")
{
btnSet.Text = "Set as Normal User";
}
else
{
btnSet.Text = "Set as Power User";
}
}
}
}
Repeater1.DataSource = dr;
Repeater1.DataBind();
dr.Dispose();
con.Close();
aspx
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<asp:Button ID="btnSet" commandname="set" commandargument=<%# Eval ("employeeid") %> runat="server" class="tiny success expand button" Text="" />
You can subscribe to the Repeater's ItemDatabound event. It allows you to access the controls of the item and change them based on the values of the current item:
private void Repeater1_ItemDatabound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// Retrieve button of the line
var btn = e.Item.FindControl("btnSet") as Button;
if (btn != null)
{
// Set text of button based on e.Item.DataItem;
}
}
}
try this its too much short and working
<asp:Button ID="btnSet" commandname="set" commandargument=<%# Eval("employeeid") %> runat="server" class="tiny success expand button" Text='<%# Eval("userType").ToString() == "2" ?"Set as Normal User" : "Set as Power User" %>' />
let me know if you need any more help
You have to use the databind event of your repeater.
Something like:
void Repeater1_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
// Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
Button btnSet = (Button)e.Item.FindControl("btnSet");
if ( e.Item.DataItem["userType"].ToString() == "2")
{
btnSet.Text = "Set as Normal User";
}
else
{
btnSet.Text = "Set as Power User";
}
}
}
I'm not able to bind my dropdownlist present in edititem template . I am getting null reference when i try to access it.
My design:
<asp:TemplateField HeaderText ="Category">
<ItemTemplate >
<asp:Label ID="drpcategory" Text ='<%#Bind("category") %>' runat ="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="drpcategory1" AppendDataBoundItems="True" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
My code behind:
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv_table1.EditIndex = e.NewEditIndex;
DropDownList drpcategory1 = ((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1"));
//BindDropDown(drpcategory1);
dt = con.GetData("Select category_name from category");
String str = gv_table1.Rows[e.NewEditIndex].FindControl("drpcategory1").GetType().ToString();
//((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1")).DataSource = dt;
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
this.setgrid();
}
I've tried looking on the net and tried many things in vain. I am new to asp. Thanks in advance. I would like the dropdown to be bound only when user enters edit mode.
Code Behind: Tested Code and also set dropdown-list selected value on edit mode
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("drpcategory1");
//bind dropdown-list
DataTable dt = con.GetData("Select category_name from category");
ddList.DataSource = dt;
ddList.DataTextField = "category_name";
ddList.DataValueField = "category_name";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = dr["category_name"].ToString();
}
}
}
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex;
gridviewBind();// your gridview binding function
}
I do it like this. In which, Name and Id are two fields of Company object:
HTML Code:
<asp:TemplateField HeaderText="Công ty">
<EditItemTemplate>
<asp:DropDownList ID="ddlCompanyEdit" DataSource="<%# PopulateddlCompanyEdit() %>" DataValueField="Id" DataTextField="Name" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbCompany" runat="server" Text='<%#Bind("Company") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
C# code behind:
protected IEnumerable<Company> PopulateddlCompanyEdit()
{
using (var bkDb = new BrickKilnDb())
{
return bkDb.Companies.ToList();
}
}
protected void gvProject_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
string Active = "";
if (e.Row.DataItem != null)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
Label lblEditActive = (Label)e.Row.FindControl("lblUP_ET_ActiveStatus");
if (lblEditActive.Text != string.Empty)
{
Active = lblEditActive.Text.Trim();
}
DropDownList ddlActive = (DropDownList)e.Row.FindControl("ddlUP_ET_ActiveStatus");
ddlActive.Items.Clear();
ddlActive.Items.Add("True");
ddlActive.Items.Add("False");
ddlActive.DataBind();
ddlActive.Items.FindByText(Active).Selected = true;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
The event RowEditing occurs just before a row is edited.
You should use the RowDataBound event instead.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (gv.EditIndex == e.Row.RowIndex &&
e.Row.RowType==DataControlRowType.DataRow)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
//bind the control
}
}
You have to use RowDataBound event to bind the dropdown control for edited row. Please use below method in RowDataBound event.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
DataTable dt = con.GetData("Select category_name from category");
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
}
}
Hope this will help you.