Duplicated Data in 1 of my 2 gridviews when using AppendDataBoundItems - c#

I have 2 gridview called DDLTOC and DDLCase. I have inserted default values into the DDL using appenddatabounditems. My default value is ("Select Member Report ID")
<asp:DropDownList ID="DDLTOC" runat="server" style="margin-top: 0px;" OnSelectedIndexChanged="DDLTOC_SelectedIndexChanged" DataTextField="typeofcrime" DataValueField="typeofcrime" AutoPostBack="True" AppendDataBoundItems="true" >
<asp:ListItem Value="-1">Select Member Report ID</asp:ListItem>
</asp:DropDownList>
DDLCase
<asp:DropDownList ID="DDLCase" runat="server" AutoPostBack="True" DataTextField="memberreportid" DataValueField="memberreportid" Height="16px" OnSelectedIndexChanged="DDLCase_SelectedIndexChanged" AppendDataBoundItems="true" >
<asp:ListItem Value="">Select Case</asp:ListItem>
</asp:DropDownList>
I have inserted data bind into my DDLTOC at the page load which will display selected value from the database once the webapp is run.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;" +
"Initial Catalog=project; Integrated Security = SSPI");
SqlDataAdapter da = new SqlDataAdapter("SELECT distinct typeofcrime FROM MemberReport where handle='handled' AND caseprogress='settled'", conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds);
DDLTOC.DataSource = ds;
DDLTOC.DataTextField = "typeofcrime";
DDLTOC.DataValueField = "typeofcrime";
DDLTOC.DataBind();
conn.Close();
}
}
I also added another bind on the DDLTOC
protected void DDLTOC_SelectedIndexChanged(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = project; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "SELECT memberreportid FROM MemberReport Where typeofcrime ='" + DDLTOC.SelectedValue + "' AND caseprogress='settled'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
DDLCase.DataSource = ds2;
DDLCase.DataTextField = "memberreportid";
DDLCase.DataValueField = "memberreportid";
DDLCase.DataBind();
}
sql = "Select username, memberreportid, location, crdatetime, citizenreport, image1, image2, image3, image4, image5 from MemberReport where typeofcrime ='" + DDLTOC.SelectedItem.Text + "' and handle='handled'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet dsSel = new DataSet();
cmdAdd.Fill(dsSel);
GVCR.DataSource = dsSel;
GVCR.DataBind();
}
connAdd.Close();
}
}
The first binding in DDLTOC_SelectedIndex basically allows the value of DDLCase to be displayed on the dropdownlist according to the value selected in the DDLTOC. The 2nd one binding will display out the necessary values from the database into a gridview. I have 2 database value that will be displayed out in the DDLTOC, Gang & Robbery. So if i were to randomly select gang, then select back to my default value then select gang and back to selecting default value, it will display out the Gang's DDLCase value twice on my DDLCase.
Why does repetitive data occurs?

Before databinding DDLCase, just clear its item collection. Modify your DDLCase databinding code portion as:
DDLCase.Items.Clear();
DDLCase.DataSource = ds2;
DDLCase.DataTextField = "memberreportid";
DDLCase.DataValueField = "memberreportid";
DDLCase.DataBind();
DDLCase.Items.Insert(0, new ListItem("Select Case", ""));
DDLCase.SelectedIndex = 0;
Alternatively you can set EnableViewState="False" in your DDLCase markup; but in that case if any other postback occurs on the page (other than DDLToc, say from a button which does not populate DDLCase again), the data of DDLCase will be lost. It is the ViewState of DDLCase which is keeping the previous state of it so that in cross requests the dropdown items are not lost. And you are just adding into its item collection unless its ViewState is disabled.

Related

Set the first value as NULL value to DropDownMenu C#

When I run application dropdown menu's value are always set to 0 and displaying result in Report.
I want to modify these to add text in DropDownMenu and when user is not selected anything it should return all data, if user select value from dropdown it should return value which user selected.
First DropDownMenu
public void FillOrgUnit()
{
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
{
string com = "SELECT DISTINCT OrgUnitID FROM tblZaposleni_AD ORDER BY OrgUnitID ASC";
SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
DataTable dt = new DataTable();
adpt.Fill(dt);
ddlOrgUnit.DataSource = dt;
ddlOrgUnit.DataTextField = "OrgUnitID";
ddlOrgUnit.DataValueField = "OrgUnitID";
ddlOrgUnit.DataBind();
ddlOrgUnit.Items.Insert(0, new ListItem("-- Izaberi Org Jedinicu --", "NULL"));
}
}
Second dropdown menu:
public void FillStatus()
{
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
{
string com = "SELECT DISTINCT Status FROM tblZaposleni_AD";
SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
DataTable dt = new DataTable();
adpt.Fill(dt);
ddlStatus.DataSource = dt;
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = "Status";
ddlStatus.DataBind();
ddlStatus.Items.Insert(0, new ListItem("-- Izaberi Status --", "NULL"));
}
}
enter image description here
HTML
<div>
<p class="auto-style1">
Izaberi Izvjestaj :
<br class="auto-style1" />
<asp:DropDownList ID="ddlReportName" runat="server" Width="168px" DataTextField="Value" DataValueField="Key" OnSelectedIndexChanged="ddlReportName_SelectedIndexChanged" Height="16px">
</asp:DropDownList>
<br class="auto-style1" />
Org Unit
<br class="auto-style1" />
<asp:DropDownList ID="ddlOrgUnit" runat="server" Height="17px" OnSelectedIndexChanged="ddlOrgUnit_SelectedIndexChanged" Width="157px" AppendDataBoundItems="True">
<asp:ListItem Value="">-- Izaberi Org Jedinicu --</asp:ListItem>
</asp:DropDownList>
<br class="auto-style1" />
Status:
<br class="auto-style1" />
<asp:DropDownList ID="ddlStatus" runat="server" Height="16px" OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged1" Width="147px" AppendDataBoundItems="True">
<asp:ListItem Value="">-- Izaberi Status --</asp:ListItem>
</asp:DropDownList>
</p>
<p class="auto-style1">
<br class="auto-style1" />
<%--Show--%>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Filter" Width="224px" />
</p>
</div>
Page_Load where I call FillStatus and FillOrgUnt metod
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string path = #"\Reports\";
CustomReportStorageWebExtension reportsStorage = new CustomReportStorageWebExtension(path);
ddlReportName.DataSource = reportsStorage.GetUrls();
ddlReportName.DataBind();
//Call function for populate cb
FillStatus();
FillOrgUnit();
}
else
{
XtraReport reportToOpen = null;
switch (ddlReportName.SelectedValue)
{
case "Zaposleni 1":
reportToOpen = new ZaposleniSaoOsig1();
break;
case "Zaposleni 2":
reportToOpen = new ZaposleniSaoOsig2();
break;
case "Zaposleni 3":
reportToOpen = new ZaposleniSaoOsig3();
break;
}
GetReports(reportToOpen);
ASPxWebDocumentViewer1.OpenReport(reportToOpen);
}
}
Main function which filters Status and OrgUnit
private void GetReports(XtraReport report)
{
try
{
string connString = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
string strproc = "TestReport";
using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.SelectCommand.Parameters.Add("#Status", SqlDbType.Bit).Value = ddlStatus.SelectedValue == "1" ? true : false;
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = ddlOrgUnit.SelectedValue;
sda.Fill(ds);
string[] arrvalues = new string[ds.Tables[0].Rows.Count];
for (int loopcounter = 0; loopcounter < ds.Tables[0].Rows.Count; loopcounter++)
{
//assign dataset values to array
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["PrezimeIme"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["NetworkLogin"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["Status"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["OrgUnitID"].ToString();
}
report.DataSource = ds;
report.DataMember = ds.Tables[0].TableName.ToString();
}
}
catch (Exception)
{
throw;
}
}
As well as stored procedure which return filtered Report by Status Or OrgId
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[TestReport]
(
#Status bit,
#OrgJed int
)
AS
BEGIN
SELECT PrezimeIme, NetworkLogin, Status, OrgUnitId, DT_Creat, DT_Modif
FROM [DesignSaoOsig1].[dbo].[tblZaposleni_AD]
WHERE (#Status IS NULL OR Status = #Status)
AND (#OrgJed IS NULL OR OrgUnitID = #OrgJed)
END
You can do the following to bind the datasource:
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
{
string com = "SELECT DISTINCT OrgUnitID FROM tblZaposleni_AD ORDER BY OrgUnitID ASC";
SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
DataTable dt = new DataTable();
adpt.Fill(dt);
ddlOrgUnit.DataSource = dt;
ddlOrgUnit.DataBind();
ddlOrgUnit.DataTextField = "text field you want to bind";
ddlOrgUnit.DataValueField = "value field you want to bind";
ddlOrgUnit.DataBind();
//add default value - you can then remove the default value from html
ddlOrgUnit.Items.Insert(0, new ListItem("-- Izaberi Org Jedinicu --","N/A")
}
The above logic should be done in the FillStatus() method too.
In your Page_Load method do the following
if (!IsPostBack)
{
FillStatus();
FillOrgUnit();
}
In the ddlOrgUnit_SelectedIndexChanged - for example - you will handle the value selected by the user accordingly - and filter for the select value - or return all.
NOTE
When you fill your DataTable(dt) from your query - you will have a table structure from the following SQL table tblZaposleni_AD
In here ddlOrgUnit.DataTextField = "text field you want to bind"; you will add the column name you want to bind as text file - eg Name
NOTE
How to use tryparse in C#
if (Int32.TryParse(ddlStatus.SelectedValue, out int theValue))
{
//is not null
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = theValue
}
// is null and you dont pass the parameter
Then in your stored procedure you set the default value for #OrgJed int to be null
ALTER PROCEDURE [dbo].[TestReport]
(
#Status bit,
#OrgJed int = NULL
)
using(sqlconnection con=new sqlconnection(cs))
{
sqlcommand cmd=new sqlcommand("select [datatextfield], [datavaluefield] from tbl",con);
sqldatareader rdr=cmd.executereader();
dropdown.datasource=rdr;
dropdown.datatextfield=rdr[0];
dropdown.datavaluefield=rdr[1];
dropdown.databind();
}

Filling the default value of a dropdown in a gridview with the current value

After some lengthy experimentation, I discovered that having this line of code on the aspx side:
<EditItemTemplate>
<asp:DropDownList ID="ddl_Project_Owner" runat="server" Width="70px"
DataTextField="Project_Owner" DataValueField="Project_Owner"
SelectedValue='<%# Bind("Project_Owner") %>' >
</asp:DropDownList>
</EditItemTemplate>
caused an index error, but removing the SelectedValue='<%# Bind("Project_Owner") %>' piece allowed the gridview to function properly. The only thing is, when the row goes into edit mode, the dropdown is not filled with the current value. It's blank. I'd like to fill it with the current value.
On the code-behind side, I use this code to fill the dropdown:
protected void DataGrid_ResourceAllocation_EditCommand(object sender, GridViewEditEventArgs e)
{
DataGrid_ResourceAllocation.EditRowStyle.BackColor = System.Drawing.Color.LightYellow;
DataGrid_ResourceAllocation.EditIndex = e.NewEditIndex;
LoadResourceAllocationGrid();
//DataGrid_ResourceAllocation.DataBind();
SqlConnection conn = GetConnection();
int RAC = DataGrid_ResourceAllocation.Rows.Count;
GridViewRow row = DataGrid_ResourceAllocation.Rows[e.NewEditIndex];
//*********************************************************
//******** Fill in all your dropdown lists here ***********
//*********************************************************
DropDownList ddList = row.FindControl("ddl_Project_Owner") as DropDownList;
string ddListVal = ddList.SelectedValue;
//DropDownList ddList = (DropDownList)e.Row.FindControl("ddl_Project_Owner");
if (ddList != null)
{
//bind dropdown-list
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
//DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = ddListVal;
}
}
I tried that "ddListVal" variable because I thought it might work, but it didn't, so you can ignore that.
Can anyone help me get my dropdown to populate with the current value that exists for that field in that record?
This error is due to this : you set selectedValeue befor binding dropdownlist.
you can bind dropdownlist in RowDataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddList= e.Row.FindControl("ddl_Project_Owner") as DropDownList;
if (ddList != null)
{
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
}
}
}

Dynamic Display of Images from Database

Redesigning an application from a set number of images stored with other items to display, to a variable number of images stored in a second table.
Found this question and have started modifying from it, but am getting a bit lost: ASP.Net Display Images in a GridView span across columns and rows? Using C#
I have the datalist control for asp.net page built, but know the path item will not work:
<asp:DataList ID="dlImages" runat="server"
RepeatColumns ="2"
RepeatDirection ="Horizontal"
RepeatLayout ="Flow">
<ItemTemplate>
<asp:Image ID="ImageQ" runat="server" Width="150px" ImageUrl='<%# Bind("ImageFile", "~/photo/{0}") %>' />
</ItemTemplate>
</asp:DataList>
But am lost trying to get the data into this list.
Originally The image data was loaded along with other information via the below:
protected void Page_Load(object sender, EventArgs e)
{
string sConstr = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
SqlConnection Conn = new SqlConnection(sConstr);
using (Conn)
{
SqlCommand command = new SqlCommand("QuestionDetail", Conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#QuestionID", SqlDbType.BigInt));
command.Parameters["#QuestionID"].Value = Convert.ToInt32(Request["Id"]);
Conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
byte[] imgBytes = (byte[])reader["ImageFile"];
string encodedBytes = Convert.ToBase64String(imgBytes);
string url = string.Concat("data:image/jpg;base64,", encodedBytes);
Image1.ImageUrl = url;
byte[] imgBytes2 = (byte[])reader["ImageFile2"];
string encodedBytes2 = Convert.ToBase64String(imgBytes2);
string url2 = string.Concat("data:image/jpg;base64,", encodedBytes2);
Image2.ImageUrl = url2;
byte[] imgBytes3 = (byte[])reader["ImageFile3"];
string encodedBytes3 = Convert.ToBase64String(imgBytes3);
string url3 = string.Concat("data:image/jpg;base64,", encodedBytes3);
Image3.ImageUrl = url3;
byte[] imgBytes4 = (byte[])reader["ImageFile4"];
string encodedBytes4 = Convert.ToBase64String(imgBytes4);
string url4 = string.Concat("data:image/jpg;base64,", encodedBytes4);
Image4.ImageUrl = url4;
txt_QuestionID.Text = reader["Id"].ToString();
txt_author.Text = reader["Author"].ToString();
txt_Date.Text = reader["SubmitDate"].ToString();
txt_Stem.Text = reader["Stem"].ToString();
txt_RespA.Text = reader["RespA"].ToString();
txt_RespB.Text = reader["RespB"].ToString();
txt_RespC.Text = reader["RespC"].ToString();
txt_RespD.Text = reader["RespD"].ToString();
txt_RespE.Text = reader["RespE"].ToString();
txt_Answer.Text = reader["Answer"].ToString();
txt_Critique.Text = reader["Critique"].ToString();
txt_KeyObjective.Text = reader["KeyObjective"].ToString();
txt_References.Text = reader["References"].ToString();
txt_Practice1.Text = reader["PracticeArea1"].ToString();
txt_Practice2.Text = reader["PracticeArea2"].ToString();
txt_Practice3.Text = reader["PracticeArea3"].ToString();
txt_Practice4.Text = reader["PracticeArea4"].ToString();
txt_IsCloneOf.Text = reader["IsCloneOf"].ToString();
}
reader.Close();
}
}
I have taken the Image portions out and am trying to process them to the DataList via a separate code block (and leave the text elements as is) and have a stored procedure that will grab the applicable records.
This section of the pageload is loading placeholders correctly based on the number of images attached to each question,,, but how to get the encoded image read instead of passing a path.....:
DataTable dt = new DataTable();
using (Conn)
{
SqlCommand ad = new SqlCommand("ImageDetail", Conn);
ad.CommandType = CommandType.StoredProcedure;
ad.Parameters.Add(new SqlParameter("#QuestionID", SqlDbType.BigInt));
ad.Parameters["#QuestionID"].Value = Convert.ToInt32(Request["Id"]);
SqlDataReader reader2 = command.ExecuteReader();
while (reader2.Read())
{
if(!Convert.IsDBNull(reader2["ImageFile"]))
{
byte[] imgBytes = (byte[])reader2["ImageFile"];
string encodedBytes = Convert.ToBase64String(imgBytes);
string url = string.Concat("data:image/jpg;base64,", encodedBytes);
}
}
reader2.Close();
dt.Load(reader2);
}
dlImages.DataSource = dt;
dlImages.DataBind();
Still a total noob, and everytime I change controls it takes me awhile to figure out how to use the new one/s. Right now The code will run with no errors,,, but no images either. I had to add the check for "IsDBNULL" as I kept getting this error. I know that the table being accessed by the ImageDetail Stored Procedure has zero null values in any record, and that the stored procedure returns records when fed a QuestionID.
Was finally able to figure this out.
Datalist control:
<asp:DataList ID="dlImages" runat="server"
RepeatColumns ="2"
RepeatDirection ="Vertical"
CellSpacing ="20"
RepeatLayout ="Table">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="200px" ImageUrl='<%# "GetImage.aspx?id=" + System.Convert.ToString(Eval("ImageID")) %>' /><br />
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ImageName") %>' Font-Bold="True" Font-Size="1.2em" ForeColor="Navy"/><br />
<asp:Label ID="Label2" runat="server" Text='<%# Eval("ImageContent") %>' Font-Italic="true"/><br /> <br />
</ItemTemplate>
DataTable definition for populating (note the datasource is previously defined on the page load event):
DataTable dt = new DataTable();
using (Conn)
{
SqlDataAdapter ad = new SqlDataAdapter("SELECT QuestionID, Images2.ImageID, ImageFile, ImageContent, ImageName, SEQ_NUM from qimages join Images2 on qimages.imageid = images2.imageid where QuestionID = #QuestionID", Conn);
ad.SelectCommand.Parameters.Add("QuestionID", SqlDbType.BigInt).Value = txt_QuestionID.Text;
ad.Fill(dt);
}
dlImages.DataSource = dt;
dlImages.DataBind();
Finally the code for the "GetImage.aspx" page the retrieves and passes the image to the datalist. This page uses only the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sImageID = Request.QueryString["id"];
string constr = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
string sQuery = "SELECT ImageFile from Images2 WHERE ImageID = #ImageID";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(sQuery, con);
cmd.Parameters.Add("#ImageID", SqlDbType.Int).Value = Int32.Parse(sImageID);
using (con)
{
con.Open();
SqlDataReader DR = cmd.ExecuteReader();
if (DR.Read())
{
byte[] imgData = (byte[])DR["ImageFile"];
Response.BinaryWrite(imgData);
}
}
}
}
This is working to display the database encoded images in two columns based on the question being looked at.
Thanks everyone for the pointers.

Error in Dropdown "SelectedIndexChanged" event, while Seleting new item from RadComboBox

In my webpage, there is a RadComboBox outside the RadGrid and a Dropdown inside RadGrid.
Data inside Dropdown is bind based on RadComboBox item selection.
Ex: If from RadComboBox, item "Company" is selected, then data inside Dropdown will be related to "Company" (i.e, Company1, Company2,company3, etc)
HTML code:
<telerik:RadComboBox ID="ddlCompany" runat="server" Height="200" Width="240"
DropDownWidth="310" EmptyMessage="- Select Product -" HighlightTemplatedItems="true" CausesValidation="false" Filter="StartsWith" AppendDataBoundItems="true" AllowCustomText="true" AutoPostBack="true" DataTextField="Title" DataValueField="Code" OnSelectedIndexChanged="ddlCompany_SelectedIndexChanged">
</telerik:RadComboBox>
<telerik:RadGrid ID="RGGSTAcCode" runat="server">
<Columns>
<telerik:GridEditCommandColumn></telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
C# Code:
public DataSet GetCompanyNames()
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("General.usp_tbl_BuyerCode_Query", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
con.Open();
da.Fill(ds);
con.Close();
}
catch (Exception ex)
{
}
return ds;
}
protected void BindComapnyDL()
{
ddlCompany.DataTextField = "Title";
ddlCompany.DataValueField = "Code";
ddlCompany.DataSource = GetCompanyNames();
ddlCompany.DataBind();
Session["Comp"] = ddlCompany.SelectedValue.ToString();
}
protected void ddlCompany_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
if (ddlCompany.SelectedItem != null)
{
SqlConnection con = new SqlConnection(strcon);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT [AccountCodeID],[AccountCode]+' - '+[AccountDescription] as[AccountDescription] FROM [Sunway_AP].[General].[tbl_AccountCode] (NOLOCK) Where [CompanyCode] = '" + Session["Comp"] + "' order by [AccountCode]+' - '+[AccountDescription]", con);
con.Open();
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
finally
{
con.Close();
}
DropDownList list = RGGSTAcCode.FindControl("ddlAcCode") as DropDownList;
list.DataTextField = "AccountDescription";
list.DataValueField = "AccountCodeID";
list.DataSource = dt;
list.DataBind();
}
else
{
Response.Write("Please select Company first");
}
}
Now, when I try to change the company using "ddlCompany_SelectedIndexChanged" event,
I get below error:
System.NullReferenceException: Object reference not set to an instance of an object.
at line :
list.DataTextField = "AccountDescription";
Please suggest what is wrong in my code. Thanks in advance
This line contains error dropdown is not properly find
DropDownList list = RGGSTAcCode.FindControl("ddlAcCode") as DropDownList;
Where did You placed Dropdown inside any control..??
visite this link http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/how-to/operations-with-ms-dropdownlist-in-edititemtemplate-of-gridtemplatecolumn
try this
foreach (GridDataItem item in RGGSTAcCode.EditItems)
{
DropDownList list = item.FindControl("ddlAcCode") as DropDownList;
//Now we can do stuff with the "list"
}
Keep in mind that the row needs to be in Edit Mode to find controls in its EditItemTemplate.

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