Dynamic Display of Images from Database - c#

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.

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();
}

Set DropDownList's SelectValue based on Database

I have a DropDownList in a GridView and I am wanting to have the selected value be whatever the value for that particular person is in the database
My ASP Code for the DropDownList:
<asp:TemplateField HeaderText="Team" SortExpression="Team">
<ItemTemplate>
<asp:DropDownList ID="ddlTeam" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Team"
DataValueField="Team" ondatabound="ddlTeam_DataBound">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
SelectCommand="SELECT DISTINCT [Team] FROM [Team_Names]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
My ddlTeam_OnBound:
protected void ddlTeam_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
foreach (ListItem item in ddl.Items)
{
if (item.Text == "valor")
{
item.Text = "Team Valor";
}
else if (item.Text == "mystic")
{
item.Text = "Team Mystic";
}
}
}
UPDATE - No Error but DDL is empty:
DropDownList ddl = new DropDownList();
string query2 = "SELECT team_name FROM sec WHERE job = " + TextBox1.Text;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query2, con))
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while(read.Read())
{
ddl.SelectedValue = read["team_name"].ToString();
}
}
con.Close();
}
}
Do everything in a query in SqlDataSource and don't use code behind without necessity.
<asp:TemplateField HeaderText="Team" SortExpression="Team">
<ItemTemplate>
<asp:DropDownList ID="ddlTeam" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Team_txt"
DataValueField="Team"><%--No need ondatabound="ddlTeam_DataBound"--%>
</asp:DropDownList><%--datasourceId must match --%>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
SelectCommand="SELECT DISTINCT [Team],case Team when 'valor' then 'Team Valor' when 'mystic' then 'Team Mystic' else Team end team_txt FROM [Team_Names]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
You aren't executing the SqlCommand or opening a SqlConnection. You should put your input into a parameter to prevent a potential SQL Injection attack.
As an example:
string teamName = string.Empty;
using (SqlConnection connection = new SqlConnection("your connection string"))
{
connection.Open();
string query = "SELECT DISTINCT team_name FROM sec WHERE job = #job";
SqlParameter param = new SqlParameter
{
ParameterName = "#job",
Value = TextBox1.Text
};
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.Add(param);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow);
if (reader.Read())
{
teamName = reader.GetString(0);
// or
int ord = reader.GetOrdinal("team_name");
teamName = reader.GetString(ord); // Handles nulls and empty strings.
}
}
}
EDIT
You also have to set up your drop down list correctly.
DropDownList ddl = new DropDownList();
ddl.DataSource = // call your database code - see above
ddl.DataValueField = "ValueProperty";
ddl.DataTextField = "TextProperty";
ddl.DataBind();
ddl.SelectedValue = teamName;

DropDownList is not showing the Selected Value in EditItemTemplate of RadGrid

I am using asp DropDownList inside RadGrid, and trying to Add and Update the DropDownList item inside Database table.
Below is the HTML code for DropDownList inside RadGrid's EditItemTemplate:
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>'></asp:Label>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
C# Code:
public DataTable GetAccCode(string CompanyCode)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("[Invoice].[usp_tbl_AccountCode_DL_Test]", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CompanyCode", CompanyCode);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
con.Close();
}
catch (Exception ex)
{
}
return dt;
}
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
DropDownList ddl = (DropDownList)item.FindControl("ddlAcCode");
ddl.DataSource = GetAccCode(CompanyCode);
ddl.DataTextField = "AccountDescription";
ddl.DataValueField = "AccountCodeID";
ddl.DataBind();
ddl.Items.Insert(0, "- Select -");
//Select particular dropdown value while "Edit"
string accCodeID = item.GetDataKeyValue("AccountCodeID").ToString();
Label lblAcCode2 = item.FindControl("lblAcCode") as Label;
//if (!string.IsNullOrEmpty(lblAcCode2.Text))
//{
ddl.SelectedValue = lblAcCode2.Text;
//}
//string SelectedVal = ddl.SelectedValue;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT [AccountCode]+' - '+[AccountDescription] as [AccountDescription] FROM [Sunway_AP].[Invoice].[tbl_AccountCodeTest] where AccountCodeID='" + accCodeID + "' ", con);
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
finally
{
con.Close();
}
ddl.SelectedValue = dt.ToString();
string SelectedVal = ddl.SelectedValue;
}
}
}
This is the Stored Procedure:
ALTER PROCEDURE [Invoice].[usp_tbl_AccountCode_DL_Test]
#CompanyCode nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT [AccountCodeID] ,[AccountCode]+' - '+[AccountDescription] as [AccountDescription]
FROM [Sunway_AP].[General].[tbl_AccountCode] (NOLOCK)
Where [CompanyCode] = #CompanyCode
order by [AccountCode]+' - '+[AccountDescription]
END
My problem is: I am unable to fetch the "DropDownList's" selected value for a particular Id (particular row of RadGrid), while Edit.
Everytime when I try to set the Selected Value of DropdownList from code behind, it shows me 1st item '- Select -' inside the selected value.
Please reply what is wrong in my code.
I am very new in Telerik. Thanks in advance.
Modified my posted code as below:
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
DropDownList ddl = (DropDownList)item.FindControl("ddlAcCode");
ddl.DataSource = GetAccCode(CompanyCode);
ddl.DataTextField="*your text field*";
ddl.DataValueField="*your Value field*";
ddl.DataBind();
ddl.Items.Insert(0, "- Select -");
Label lblAcCode2 = item.FindControl("lblAcCode2") as Label;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
ddl.SelectedItem.Text = lblAcCode2.Text;
ddl.SelectedValue = lblAcCode2.Text;
}
}
}
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
Hope this helps...
All the best...

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.

How to delete a row from DB (*.mdb) in c#

I have an access DB (.mdb) named: Programs, with one table named: Data. By using the DataGridView I present the data from the table Data. I want to delete a row from the DataGridView and from the DB during runtime. Does anyone know how to do that (using C#)?
Another question I have is, who can i run queries on my DB?
thanks!
Very simple.
I suppose in your datagrid you have a check box by choosing which you will be able to choose the rows that you want to delete. And assuming you have a submit button, so after choosing the rows click on the submit button. In the button's click event call the Delete query say delete from tblname where id = #id [#id is the id that will be passed from your grid]
After that just populate the grid e.g. select * from tblname
e.g.
Aspx code
<asp:GridView runat="server" ID="gvTest" Width="100%" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="5%">
<ItemTemplate>
<asp:CheckBox ID="chkDel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="RegID" DataField="RegID" ItemStyle-Width="10%">
<ItemStyle HorizontalAlign="Left"/>
</asp:BoundField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="22%" ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Width="100%" Text= '<%# DataBinder.Eval(Container.DataItem, "UserName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click"></asp:Button>
Submit button cilck event's code
protected void btnSubmit_Click(object sender, EventArgs e)
{
for (int count = 0; count < gvTest.Rows.Count; count++ )
{
CheckBox chkSelect = (CheckBox)gvTest.Rows[count].FindControl("chkDel");
if (chkSelect != null)
{
if (chkSelect.Checked == true)
{
//Receiveing RegID from the GridView
int RegID = Int32.Parse((gvTest.Rows[count].Cells[1].Text).ToString());
object result = DeleteRecord(RegID); //DeleteRecord Function will delete the record
}
}
}
PopulateGrid(); //PopulateGrid Function will again populate the grid
}
public void DeleteRecord(int RegId)
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlConnection connection = new SqlConnection(#connectionPath);
command = "delete from tblname where id = " + RegId
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(command, connection);
cmd.ExecuteNonQuery();
}
catch (SqlException sqlExcep) {}
finally
{
connection.Close();
}
}
public void PopulateGrid()
{
DataTable dt = new DataTable();
dt = GetRecord();
if(dt !=null && dt.rows.count>0)
{
gvTest.DataSource = dt;
gvTest.DataBind();
}
}
public DataTable GetRecord()
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlConnection connection = new SqlConnection(#connectionPath);
command = "Select * from tblname" ;
connection.Open();
SqlCommand sqlCom = new SqlCommand(command, connection);
adapter.SelectCommand = sqlCom;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
Hope this makes sense.

Categories

Resources