SelectedValue of DropDownlList - c#

I have a gridview that has dropdownlist in edit section, I want to bind the selectedvalue from database when editing. In designer section there is no SelectedValue attribute, it gives runtime error. What to do any help?? Is there any way to handle it from code-behind?
<asp:TemplateField HeaderText="Company">
<EditItemTemplate>
<asp:DropDownList ID="DDLCompany" runat="server" DataValueField="cname" DataTextField="cname" SelectedValue = '<%# Bind("cname") %>' >
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CompanyLabel" runat="server" Text='<%# Bind("cname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList DDLCompany = (DropDownList)e.Row.FindControl("DDLCompany");
DropDownList DDLPrinter = (DropDownList)e.Row.FindControl("DDLPrinter");
if (DDLCompany != null)
{
DDLCompany.DataSource = userobj.FetchCompanyList();
DDLCompany.DataBind();
DDLCompany.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[0].ToString();
}
if (DDLPrinter != null)
{
DDLPrinter.DataSource = userobj.FetchPrinterList();
DDLPrinter.DataBind();
DDLPrinter.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[0].ToString();
}
}
}

In Codebehind you have to check
for e.Row.RowType==
DataControlRowType.DataRow &&
e.Row.RowState ==
DataControlRowState.Edit in
RowDataBound before you find your
Dropdwonlist.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.dataitem.aspx
On aspx you can set the
seletcedvalue in the following way:
http://msdn.microsoft.com/en-us/library/ms178294.aspx

Related

Add Event on specific control in the gridview

I have a scenario, where i need to attach an event (textchanged) to a textbox. It should only trigger, if the code is "code2". Please check the below code ; The value_TextChanged doesn't get triggered:
<asp:GridView runat="server" ID="gv1" AutoGenerateColumns="false"
onrowcreated="gv1_RowCreated1" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="code" Text='<%# Bind("[code]") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" ID="val" Text='<%# Bind("[value]") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}
void DataBind()
{
DataTable dt = new DataTable();
dt.TableName = "tb1";
dt.Columns.Add("code");
dt.Columns.Add("value");
dt.Rows.Add("code1", "Red");
dt.Rows.Add("code2", "Green");
dt.Rows.Add("code3", "Blue");
gv1.DataSource = dt;
gv1.DataBind();
}
protected void gv1_RowCreated1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string code = (String)DataBinder.Eval(e.Row.DataItem, "code");
TextBox value = (TextBox)e.Row.FindControl("val");
if (code == "code2")
{
value.AutoPostBack = true;
value.TextChanged += new EventHandler(value_TextChanged);
}
}
}
void value_TextChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}
To trigger TextChange you need to add AutoPostBack="true" in your Markup; For attaching an event with TextChange you need not to depend gv1_RowCreated that also you can specify in the markup.
<asp:TextBox AutoPostBack="true" OnTextChanged="value_TextChanged"
runat="server" ID="val" Text="" ></asp:TextBox>
Please note one more thing, the event will trigger when the textBox
loss its focus

How to get the modified textbox value in c#?

I used a textbox in gridview to bind a value from db during pageload..
The problem is when i change the textbox value i could not get the modified value in c#, instead it gives the original value which had been there before i modified..
I am using nested GridViews...
kindly help me..
<asp:TemplateField HeaderText="Singles" >
<ItemTemplate>
<asp:HiddenField ID="hidqua" runat="server" Value='<%#bind("QualityName") %>' />
<asp:HiddenField ID="hidfau" runat="server" Value='<%#bind("FaultName") %>' />
<asp:TextBox ID="asptxtsingleg" runat="server" Text='<%# bind("singles") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
and below is my c# Coding
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "update")
{
foreach (GridViewRow row in grdInspection.Rows)
{
HiddenField hv = (HiddenField)row.FindControl("hidval");
GridView txtsi = (GridView)row.FindControl("grdInsiewChid");
foreach (GridViewRow row1 in txtsi.Rows)
{
HiddenField htn = (HiddenField)row1.FindControl("hdnPLength");
GridView nesgrid = (GridView)row1.FindControl("GridView1");
foreach (GridViewRow row2 in nesgrid.Rows)
{
HiddenField qn = (HiddenField)row2.FindControl("hidqua");
TextBox t = (TextBox)row2.FindControl("asptxtsingleg");
}
}
}
}
}
Assuming you are using button to fire the RowCommand event.
<asp:TemplateField HeaderText="Singles">
<ItemTemplate>
<asp:TextBox ID="asptxtsingleg" runat="server" Text='<%# Eval("singles") %>' Width="120px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Update" CommandName="updateData" CommandArgument='<%# Eval("Your_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
Code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "updateData")
{
//int i = Convert.ToInt32(e.CommandArgument);
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
TextBox tb = (TextBox)row.FindControl("asptxtsingleg");
}
}
You can use below code to get the text box value in RowUpdating event
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox t= (TextBox)row.FindControl("asptxtsingleg");

Set backcolor of a Gridview control, when it is enabled or disabled

In my gridview controls are enabled or disabled depending on user roles. I want to change the background color to yellow for enabled controls. I have tried to do it in RowCreated as below but all the cells are enabled at that time.
protected void begv_OrderDetail_RowCreated(object sender, GridViewRowEventArgs e)
{
foreach (TableCell cell in e.Row.Cells)
{
if (cell.Enabled == true)
{
}
else
{
//Never enters this area
}
}
}
Here is an example field in my gridview where I enable or disable the controls.
<asp:TemplateField HeaderText="ReasonCode" SortExpression="ReasonCode">
<HeaderTemplate>
<asp:Label ToolTip="ReasonCode" runat="server" Text="RC"></asp:Label>
</HeaderTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_ReasonCode" onchange="disableNextStatusButtons()" runat="server" Text='<%# Bind("ReasonCode") %>'
Enabled='<%# (Roles.IsUserInRole("İhracat Uzmanı") && Session["Status"].ToString()=="3") %>'
Width="40px"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
You can set the BackColor too in using the data binding syntax
<asp:TextBox ID="txt_ReasonCode"
onchange="disableNextStatusButtons()"
runat="server"
Text='<%# Bind("ReasonCode") %>'
Enabled='<%# (Roles.IsUserInRole("İhracat Uzmanı") && Session["Status"].ToString()=="3") %>'
BackColor='<%# (Roles.IsUserInRole("İhracat Uzmanı") && Session["Status"].ToString()=="3") ? System.Drawing.Color.Red: System.Drawing.Color.Green %>'
Width="40px">
</asp:TextBox>
A little ugly, but will work just fine.
You can go through the following step
check the user role on RowDatabound
On RowDatabound change the color of the row
protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//check role
if (condition)
e.Row.BackColor = Color.Red;
else
e.Row.BackColor = Color.Green;
//or set you individual control background
//get any control
var chk = (CheckBox)e.Row.FindControl("chkb");
//set background
chk.BackColor = Color.Red;//etc
}
}
You can set css dynamically to the textbox CssClass="yourcss"
<asp:TextBox ID="txt_ReasonCode" onchange="disableNextStatusButtons()" runat="server" Text='<%# Bind("ReasonCode") %>'
Enabled='<%# (Roles.IsUserInRole("İhracat Uzmanı") && Session["Status"].ToString()=="3") %>'
CssClass='<%# (Roles.IsUserInRole("İhracat Uzmanı") && Session["Status"].ToString()=="NormalCss").ToString()=="true"?"yellowcss":"othercss" %>'
Width="40px"></asp:TextBox>
Try it in RowDataBound event of the Gridview.
Try to use DataBound event to iterate thru all cells and update the bg.

C# getting selected value from dropdownlist in gridview asp net

How can I change the value of a textbox whenever a dropdownlist within a gridview has its value changed?
On page load, the textbox shows the selected value, but when I change the selection of the dropdownlist, the textbox value doesn't change.
The code is below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField HeaderText="Entry">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duty">
<ItemTemplate>
<asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind is below.
protected void ddl1_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
Duty dy = new Duty();
dt = dy.getdutyid(Convert.ToInt32(dropcontractid.SelectedValue));
DropDownList ddl = (DropDownList)sender;
ddl.DataSource = dt;
ddl.DataTextField = "dutyid";
ddl.DataValueField = "dutyid";
ddl.DataBind();
TextBox1.Text = ddl.SelectedValue;
}
}
You need to use SelectedIndexChanged handler to show selected value:
Markup:
<asp:DropDownList ID="duty" runat="server" OnLoad="ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged"></asp:DropDownList>
Code-behind:
protected void duty_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
DropDownList duty= (DropDownList) gvr.FindControl("duty");
TextBox1.Text = duty.SelectedItem.Value;
}
I had a similar problem using the DropDownLists in GridView. My solution was to adjust the onLoad for the dropdown so that it wouldn't re-write the DropDownList on every post back. This way if there's something there then it won't re-populate it.
protected void dropDownLoad(object sender, EventArgs e)
{
DropDownList dropDown = sender as DropDownList;
if (dropDown.SelectedValue == null || dropDown.SelectedValue == "")
{
// Your Code to populate table
}
}
You should look into using data binding instead. You can bind the textbox.Text to the selecteditem.value, this will ensure that proper updating takes place
this happens to me once then i code like this... but i didnt use the onLoad attribute, tell me if this works,
<asp:TemplateField HeaderText="duty" SortExpression="duty">
<EditItemTemplate>
<asp:TextBox ID="duty" runat="server" Text='<%# Bind("duty_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblduty" runat="server" Text='<%# Eval("duty_Name") %>' />
<asp:DropDownList ID="ddlduty" runat="server" CssClass="dropdownlist"
OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" Visible = "false"
>
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle Width="5%" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

Find out a CHECKBOX in a DATAGRID in ASP.NET

I have a GRIDVIEW and with several CHECKBOXS.
When i selected a CHECKBOX I need run some code.
To detect it, I use an EVENT HANDLER for the CHECKBOX included in a GRIDVIEW.
I cannot access the CHECKBOX with my wrong code.
Do you have any idea what I am doing wrong? Thanks for your help. Bye
ASPX
<asp:Label ID="uxMessageDisplayer" runat="server" Visible="False" EnableViewState="False"></asp:Label>
<asp:GridView ID="uxUserListDisplayer" runat="server" AutoGenerateColumns="False"
OnRowDataBound="uxUserListDisplayer_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:CheckBox ID="uxActiveCheckBoxSelector" runat="server" AutoPostBack="true" OnCheckedChanged="uxRoleCheckBoxSelector_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Users">
<ItemTemplate>
<asp:Label runat="server" ID="uxUserNameLabelDisplayer" Text='<%# Container.DataItem %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkEditButton" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkDeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CODE BEHIND
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Reference the CheckBox that raised this event
//CheckBox uxActiveCheckBoxSelector = sender as CheckBox;
CheckBox activeCheckBox = (CheckBox)FindControl("uxActiveCheckBoxSelector");
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
uxMessageDisplayer.Enabled = false;
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
uxMessageDisplayer.Enabled = false;
}
}
If I am not mistaken by your question, you are trying to set the text of the label on the same row with the checkbox based on its checked status.
Below is the code snippet I tried on my pc, hope it helps.
.aspx:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;
//create dummy data
List<string> rows = new List<string>();
Enumerable.Range(1, 5).ToList().ForEach(x => rows.Add(x.ToString()));
//bind dummy data to gridview
GridView1.DataSource = rows;
GridView1.DataBind();
}
protected void CheckBox1_CheckChanged(object sender, EventArgs e)
{
//cast sender to checkbox
CheckBox CheckBox1 = (CheckBox)sender;
//retrieve the row where checkbox is contained
GridViewRow row = (GridViewRow)CheckBox1.NamingContainer;
//find the label in the same row
Label Label1 = (Label)row.FindControl("Label1");
//logics
if (CheckBox1 != null) //make sure checkbox1 is found
{
if (CheckBox1.Checked)
{
if (Label1 != null) //make sure label1 is found
{
Label1.Text = "Checked";
}
}
else
{
if (Label1 != null)
{
Label1.Text = "Unchecked";
}
}
}
}
I'm assuming the event handler is actually registered to the checkbox.
CheckBox activeCheckBox = (CheckBox)sender;
what is "uxActiveCheckBoxSelector" and why are you ignoring sender?
Code corrected as suggest!
Usefull resource for beginners
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Cast sender to CheckBox
CheckBox activeCheckBox = (CheckBox)sender;
// Retrieve the row where CheckBox is contained (NamingContainer used to retrive parent control
GridViewRow row = (GridViewRow)activeCheckBox.NamingContainer;
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
}
}

Categories

Resources