DropDownList not getting populated from Stored Procedure - javascript

I have a quick question. I have a dropDownList that I'm trying to get populated with id's from a stored procedure. However it doesn't seem to work. this is my dropDownlist:
<div id="newExpenseTypeDialog" style="display:none;">
<label>Select new CaseFile:</label>
<asp:DropDownList runat="server" ID="ddlCaseFiles" DataSourceID="dsMyCaseFiles" DataTextField="Display" DataValueField="FileID" OnPreRender="ddl_PreRender" Width="524px" />
</div>
And this is my DataSource:
<asp:SqlDataSource ID="dsMyCaseFiles" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="System.Data.SqlClient" SelectCommand="p_CaseFiles_ListActiveCaseFilesAssignedTo" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:SessionParameter Name="InvestigatorID" SessionField="InvestigatorID" />
<asp:SessionParameter Name="AssignedTo" SessionField="InvestigatorID" />
</SelectParameters>
</asp:SqlDataSource>
My Stored procedure needs two parameter. InvestigatorID and AssignedTo. It will then find return all the FileID's that match.
Now this is my .aspx.cs side code :
(Page_load)
if (Request.QueryString["ExpenseID"] != null)
{
if (!IsPostBack)
{
ddlCaseFiles.DataSourceID = "dsCaseFiles";
ddlCaseFiles.DataTextField = "Display";
ddlCaseFiles.DataValueField = "FileID";
}
}
and my Pre_Render:
protected void ddl_PreRender(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
try
{
if (ddl.Items[0].Value != "-1")
ddl.Items.Insert(0, new ListItem("--Select--", "-1"));
}
catch
{
ddl.Items.Insert(0, new ListItem("--Select--", "-1"));
}
}
The list has the pre_render working and what not, just no data from my stored procedure.

i think you just forget to call DataBind method
ddlCaseFiles.DataBind();
in if(!ispostback) block after that three line

You haven't Binded your dropdown list yet
if (Request.QueryString["ExpenseID"] != null)
{
if (!IsPostBack)
{
ddlCaseFiles.DataSourceID = "dsCaseFiles";
ddlCaseFiles.DataTextField = "Display";
ddlCaseFiles.DataValueField = "FileID";
ddlCaseFiles.DataBind(); //You need to Bind it here
}
}
Hope this will help you

Related

RegisterStartupScript shows message after function ends

i want to show a javascript confirm box on the client side under OnChange event "chkIsActive_CheckedChanged". i am using registerStartupscript int the code behind for this purpose. this confirm message is displaying fine but it is displaying after end of the event "chkIsActive_CheckedChanged". i want to display the confirm message while executing in the function. Please help me out.
My HTML
<asp:CheckBox ID="lbl_IsActive" runat="server" OnCheckedChanged="chkIsActive_CheckedChanged" AutoPostBack="true" Checked='<%# Eval("IsActive") %>' ></asp:CheckBox>
My javascript
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.getElementById("<%=IsChecked.ClientID%>");
if (confirm("Do you want to save data?")) {
confirm_value.value = "1";
} else {
confirm_value.value = "0";
}
}
</script>
my C# code behind
protected void chkIsActive_CheckedChanged(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "Confirm();", true);
string confirmValue = IsChecked.Value;
if (confirmValue == "1")
{
string CarEstimateID = "";
Entities.CarEstimateFirms ObjEst = new Entities.CarEstimateFirms();
CheckBox chk = (CheckBox)sender;
GridViewRow gr = (GridViewRow)chk.Parent.Parent;
CarEstimateID = (GridView1.Rows[gr.RowIndex].FindControl("lbl_CarEstimateFirmID") as Label).Text; // GridView1.DataKeys[gr.RowIndex].Value.ToString();
ObjEst.CarEstimateFirmID = Convert.ToInt32(CarEstimateID);
ObjEst.IsActive = chk.Checked;
BLL.Common.UpdateCarEstimateFirms(ObjEst);
BindGridView();
}
}
Add onchange javascript event in your checkbox:
<asp:CheckBox ID="lbl_IsActive" runat="server" OnCheckedChanged="chkIsActive_CheckedChanged" AutoPostBack="true"
Checked='<%# Eval("IsActive") %>' onchange="javascript:return Confirm();" ></asp:CheckBox>
Your javascript confirm method should be like below:
<script type = "text/javascript">
function Confirm() {
if (confirm("Do you want to save data?")) {
return true;
} else {
return false;
}
}
</script>
And remove below line from chkIsActive_CheckedChanged event from code behind:
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "Confirm();", true);

How to highlight different days with different colors in calendar asp.net

i created calendar control that highlight the selected dates. but i dont know how to use different colors for each day.
<asp:Calendar ID="Calendar1" runat="server"
Height="365px" Width="594px" CssClass="myCalendar"
OnDayRender="Calendar1_DayRender" OnSelectionChanged="Calendar1_SelectionChanged" >
<DayHeaderStyle
CssClass="myCalendarDayHeader"/>
<DayStyle CssClass="myCalendarDay" Font-Bold="True" Font-Names="Cordia New"
Font-Size="30px"/>
<SelectedDayStyle
CssClass="myCalendarSelector" BackColor="#3366FF"/>
<SelectorStyle Wrap="True" CssClass="myCalendarSelector"/>
<TitleStyle
CssClass="myCalendarTitle" />
<TodayDayStyle CssClass="myCalendarToday"/>
</asp:Calendar>
....
public static List<DateTime> list = new List<DateTime>();
Hashtable HolidayList;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
List<DateTime> newList = (List<DateTime>)Session["SelectedDates"];
foreach (DateTime dt in newList)
{
Calendar1.SelectedDates.Add(dt);
}
list.Clear();
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsWeekend == true)
{
e.Cell.Enabled = false;
e.Day.IsSelectable = false;
e.Cell.BackColor = System.Drawing.Color.Gray;
}
if (e.Day.IsSelected == true)
{
list.Add(e.Day.Date);
e.Day.IsSelectable = false;
}
Session["SelectedDates"] = list;
}
i would like to add a radio button so that i can change color for example radio one is blue radio two is yellow. can anyone have an idea?
Ok, try this
Add a RadioButtonList with AutoPostBack="true" and OnSelectedIndexChanged event to your markup as follows.
<asp:Calendar ID="Calendar1" runat="server" Height="365px" Width="594px" CssClass="myCalendar"
OnDayRender="Calendar1_DayRender" OnSelectionChanged="Calendar1_SelectionChanged" >
<DayHeaderStyle
CssClass="myCalendarDayHeader"/>
<DayStyle CssClass="myCalendarDay" Font-Bold="True" Font-Names="Cordia New"
Font-Size="30px"/>
<SelectedDayStyle
CssClass="myCalendarSelector" BackColor="#3366FF"/>
<SelectorStyle Wrap="True" CssClass="myCalendarSelector"/>
<TitleStyle
CssClass="myCalendarTitle" />
<TodayDayStyle CssClass="myCalendarToday"/>
</asp:Calendar>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
And, in your code behind implement the OnSelectedIndexChanged event as follows
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
System.Drawing.Color selColor;
switch(RadioButtonList1.SelectedValue)
{
case "Red": selColor = System.Drawing.Color.Red;
break;
case "Yellow": selColor = System.Drawing.Color.Yellow;
break;
default: selColor = System.Drawing.Color.Green;
break;
}
Calendar1.SelectedDayStyle.BackColor = selColor;
}
That's it! Your selected dates will get highlighted with the color you select in the RadioButtonList control. Have fun!

Why is AutoPostBack trying to load a page if I only have it for set for a DropDownList in an update panel

I have a DropDownList in a popup where I am trying to get a user's input. I also have a "onselectedIndexChanged" for getting the users input. I have my entire DropDownList in an updatePanel so that only the DropDownList gets updated.(the popup is built using JQuery/JS) I user JS to the hiddenfield value then pass it to another function)
Here is my code :
<div id="ddlFiles">
<label>
Select new CaseFile:</label>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<asp:DropDownList runat="server" ID="ddlCaseFilesNew" DataSourceID="dsCaseFiles"
DataTextField="Display" DataValueField="FileID" OnPreRender="ddl_PreRender" Width="300px"
AutoPostBack="true" OnSelectedIndexChanged="ddlCaseFilesNew_SelectedIndexChanged">
<asp:ListItem>Item 1</asp:ListItem>
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlCaseFilesNew" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</div>
and here is my selectedIndexChanged:
<script runat="server">
protected void ddlCaseFilesNew_SelectedIndexChanged(object sender, EventArgs e)
{
hidNewCaseFile.Value = ddlCaseFilesNew.SelectedItem.Value;
}
</script>
Now for some reason as soon as I select something from the list it sends me to a "cannot find resource " page. I don't know why it does that. My url looks like this:
http://localhost:49355/base/Expenses/ViewExpenses.aspx?CaseFileID=2001
When I try to select a value, it opens that error (cannot find resource) page and says I can't find the link.
Here is a picture of the error:
Page_load:
Response.Cache.SetAllowResponseInBrowserHistory(false);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
if (!isLoggedIn())
return;
if (Request.QueryString["ExpenseID"] != null)
{
if (!IsPostBack)
{
ddlCaseFilesNew.DataSourceID = "dsCaseFiles";
ddlCaseFilesNew.SelectedIndex = -1;
ddlCaseFilesNew.DataTextField = "Display";
ddlCaseFilesNew.DataValueField = "FileID";
ddlCaseFilesNew.DataBind();
if (Request.QueryString["CaseFileID"] != null) // from view>casefiles>casefile#>notes
hidCaseFile.Value = Request.QueryString["CaseFileID"].ToString();
}
}
if (Request.QueryString["CaseFileID"] != null) // from view>casefiles>casefile#>notes
hidCaseFile.Value = Request.QueryString["CaseFileID"].ToString();
else if (Request.QueryString["FileID"] != null && Request.QueryString["TaskID"] != null) // from view>task>specific task notes
{
hidCaseFile.Value = Request.QueryString["FileID"].ToString();
hidTaskID.Value = Request.QueryString["TaskID"].ToString();
}
}
protected void ddl_PreRender(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
try
{
if (ddl.Items[0].Value != "-1")
ddl.Items.Insert(0, new ListItem("--Select--", "-1"));
}
catch
{
ddl.Items.Insert(0, new ListItem("--Select--", "-1"));
}
}
Try setting UpdateMode="Conditional" for your UpdatePanel and then try agaian..
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">

Adding new rows dynamically in a grid view or datatable in asp.net?

I am binding the grid view using data table.
My task is to add new rows to my grid view dynamically when the user clicks "ADD" button in grid view it should generate new row with three text boxes.
For example: When I click the add button in the second row, a new row should be created below the second row with three text box where the user can enter details.
Can anybody help me resolve this problem? Either in jQuery/JavaScript or on the server side.
you could try this solution
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
inside code behind
Here’s the code block below:
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
//dr = dt.NewRow();
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
in page load you have to call this method
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
this is the method for generating the rows when clicking the Button. Here are the code blocks below:
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");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
drCurrentRow["Column1"] = box1.Text;
drCurrentRow["Column2"] = box2.Text;
drCurrentRow["Column3"] = box3.Text;
rowIndex++;
}
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState
ViewState["CurrentTable"] = dtCurrentTable;
//Rebind the Grid with the current data
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
this is setpreviousdata method...
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 1; 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++;
}
}
}
}
button click event for adding new row
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
and pls take a look below image how it will generate new rows....
I hope it will helps you.....
You can use fnOpen http://www.datatables.net/ref#fnOpen. It will let you add a row directly below the row you give it. you can give that new row the html you want it to have as well.

Enable/disable text box placed in gridview on check event of check box with javascript

I have gridview which contains check box and textbox in different item template fields. Text boxes will be disbled when grid is loaded. Now what I want is, when user checks any of the check box, respected textbox in that particular row should be enabled. When user unchecks the checked checkbox, again the textbox should get clear and disable. Now when user clicks on the save button, a javascript should validate all the textbox whose respected checkboxes are checked.
Validation is
(1)Text boxes should not be empty
(2)It should allow only character and space(I want to enter name in that text box). How can I write java script to perform all this task. I am novice to javascript and completely unaware of its concept.
Thanks in advance
<script type="text/javascript">
var nameRegex = /^[a-zA-Z ]+$/;
function validateName(sender, args) {
args.IsValid = nameRegex.test(args.Value);
}
</script>
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false" DataKeyNames="Id" >
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" OnCheckedChanged="SelectRow" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:TemplateField HeaderText="Name" >
<ItemTemplate>
<asp:TextBox runat="server" ID="NameTextBox" Enabled="false" Text='<%# Eval("Name") %>' />
<asp:CustomValidator runat="server" ID="NameValidator" ControlToValidate="NameTextBox"
ValidateEmptyText="true" Text="!" Display="Static" Enabled="false"
ClientValidationFunction="validateName" OnServerValidate="ValidateName" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
public partial class WebForm1 : System.Web.UI.Page
{
private static readonly Regex nameRegex = new Regex("^[a-zA-Z ]+$");
protected void ValidateName(object source, ServerValidateEventArgs args)
{
args.IsValid = nameRegex.IsMatch(args.Value);
}
protected void SelectRow(object sender, EventArgs e)
{
Page.Validate();
var checkBox = (CheckBox)sender;
if (Page.IsValid || !checkBox.Checked)
{
var textBox = (TextBox)checkBox.NamingContainer.FindControl("NameTextBox");
var nameValidator = (CustomValidator)checkBox.NamingContainer.FindControl("NameValidator");
textBox.Enabled = checkBox.Checked;
nameValidator.Enabled = checkBox.Checked;
if (!checkBox.Checked)
textBox.Text = "";
}
else
{
checkBox.Checked = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = from item in Enumerable.Range(0, 10)
select new
{
Id = item,
Name = ""
};
GridView1.DataBind();
}
}
}

Categories