Deleting checked records from table in asp.net [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am not able to recognize what I am doing wrong in my code. Can someone help ? I want to delete all the images which are checked using c# .
my code snippet looks like this :-
SqlConnection con = new
SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
SqlDataAdapter adap;
DataSet ds;
string Query;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
protected void binddata()
{
string str = "select * from photos";
SqlCommand cmd = new SqlCommand(str, con);
adap = new SqlDataAdapter(str, con);
ds = new DataSet();
adap.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
con.Open();
String mySQL;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)
Repeater1.Items[i].FindControl("CheckBox1");
if (((CheckBox)Repeater1.Items[i].FindControl("CheckBox1")).Checked)
{
//This assumes data type of messageID is integer, change (int) to the right type
CheckBox CheckBox = (CheckBox)Repeater1.Items[i].FindControl("CheckBox1");
Literal litMessageId = (Literal)Repeater1.Items[i].FindControl("literal1");
string Id = litMessageId.Text;
mySQL = string.Format("delete from photos where id = '{0}'", Id);
SqlCommand cmdDelete = new SqlCommand(mySQL, con);
cmdDelete.ExecuteNonQuery();
// Continue your code here
}
else
{
}
}
}
catch
{
Label2.Text = "errror";
}
}
.aspx page contains :-
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<img src='images/<%#DataBinder.Eval(Container.DataItem,"images") %>' height="150" width="150" alt="" border="0" />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</br>
</ItemTemplate>
</asp:Repeater>
Thanks in advance :)

Here are some pointers:
The names you use are difficult to understand in your codebehind. You now have 1 repeater but in case you have multiple it is better to use a more specific name.
Depending on the .NET version you can use generic types to declare your variables.
SqlCommand cmd = new SqlCommand(str, con);
becomes:
var sqlCommand = new SqlCommand(queryString, connectionString);
Your not closing the connection. If your in newer versions of .NET the best approach would in my opinion be:
private string ConnectionString = webConfigurationManager.ConnectionStrings["connectionstring"] != null ? WebConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString : "";
if (!string.IsNullOrEmpty(this.ConnectionString))
{
using (var sqlConnection = new SqlConnection(this.ConnectionString))
{
//your code here
}
}
You are catching an error but your not doing anything with the provided information.
use:
Catch (Exception exception)
{
ErrorLabel.Text = string.format("The following error has occurred: {0}.", exception.Message);
}
to use the exception.Message where desired.
In modern implementations you are most probably better off using an MVC application using EntityFramework and MVC Razor.
Defining your SQL queries like that is dangerous also. If I edit the post value of the literal to something like "ID AND 1 = 1" I will now delete all photos.
Here are some pages to help you get started with Entityframework and MVC:
http://www.asp.net/mvc/tutorials
http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B
I will give you some good pointers in improvements in a minute. First try this and change the literal value to the column you use as an id in case I got it wrong:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<img src='images/<%#DataBinder.Eval(Container.DataItem,"images") %>' height="150" width="150" alt="" border="0" />
<asp:Literal ID="Literal1" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"id") %>'></asp:Literal>
</br>
</ItemTemplate>
</asp:Repeater>
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
SqlDataAdapter adap;
DataSet ds;
string Query;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
protected void binddata()
{
string str = "select * from photos";
SqlCommand cmd = new SqlCommand(str, con);
adap = new SqlDataAdapter(str, con);
ds = new DataSet();
adap.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
con.Open();
String mySQL;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)Repeater1.Items[i].FindControl("CheckBox1")
Literal litMessageId = (Literal)Repeater1.Items[i].FindControl("literal1");
if (CheckBox1 != null && litMessageId != null && CheckBox1.Checked)
{
string Id = litMessageId.Text;
mySQL = string.Format("delete from photos where id = '{0}'", Id);
SqlCommand cmdDelete = new SqlCommand(mySQL, con);
cmdDelete.ExecuteNonQuery();
// Continue your code here
}
else
{
}
}
}
catch
{
Label2.Text = "error";
}
}

Related

Dropdownlist SelectIndexChanged Not firing C#

I don't get on well with post back/DDL's.. yes I have used autopostback = true!
Below, I am trying to get the selected index changed... to fire on budgetDDL1 however, whatever I try it doesn't!
I'm binding data from a DB to the ddl...
I've tried binding/adding the ddl to the table inside/outside the post backs and enabling/disabling the view states etc.. none of this works.. there must be an easy answer?!
In what order do I need to create/bind the dropdowns for the index changed method to fire an explanation would be useful too!
DropDownList budgetDDL1 = new DropDownList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string QueryString = "SELECT [BudgetCode], [Department], CONCAT([BudgetCode],' - ', [Department]) AS 'textvalue' FROM [tblBudget]";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(QueryString, myConnection))
{
myConnection.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);
budgetDDL1.SelectedIndex = 0;
budgetDDL1.DataSource = dt;
budgetDDL1.DataTextField = "textvalue";
budgetDDL1.DataValueField = "BudgetCode";
budgetDDL1.AutoPostBack = true;
budgetDDL1.SelectedIndexChanged += budgetDDL1_SelectedIndexChanged;
budgetDDL1.DataBind();
}
}
}
table1.Controls.Add(budgetDDL1);
}
protected void budgetDDL1_SelectedIndexChanged(object sender, EventArgs e)
{ *I have a breakpoint here which doesn't fire*
string msg = budgetDDL1.SelectedItem.Text;
ScriptManager.RegisterClientScriptBlock(sender as System.Web.UI.Control, this.GetType(), "alert", "alert('" + msg + "')", true);
}
view:
<body>
<form runat="server">
<table>
<tr>
<td id="table1" runat="server">
</td>
</tr>
</table>
</form>
</body>
Place auto post back code out side of the !IsPostback
DropDownList budgetDDL1 = new DropDownList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string QueryString = "SELECT [BudgetCode], [Department], CONCAT([BudgetCode],' - ', [Department]) AS 'textvalue' FROM [tblBudget]";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(QueryString, myConnection))
{
myConnection.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);
budgetDDL1.SelectedIndex = 0;
budgetDDL1.DataSource = dt;
budgetDDL1.DataTextField = "textvalue";
budgetDDL1.DataValueField = "BudgetCode";
}
}
}
budgetDDL1.AutoPostBack = true;
budgetDDL1.SelectedIndexChanged += budgetDDL1_SelectedIndexChanged;
budgetDDL1.DataBind();
table1.Controls.Add(budgetDDL1);
}
Dynamic controls should be added on Init. After OnLoad finishes executing ASP.NET starts processing control's events and values. You can read/write their properties on or after Load.
Suggest you to check the place where you have created DropDownList.
Answer: because you have created DropDownList after the events have been processed.
Have a look here: https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx

ASP.net: ReportViewer not displaying (parameters from dynamically created textboxes)

I have an existing code that displays a reportserver RDL report in a reportviewer. I prompt the user for inputs and those are then passed as parameters to a store procedure in Sql Server.
The report generates properly as proof of concept with hard-coded number of textboxes, but obviously not all reports will have the same number of parameters. So here is my working code and the screenshot:
Working Report
ASP.NET
<%# Page Language="C#" Trace="true" AutoEventWireup="true" CodeBehind="Reports.aspx.cs" Inherits="FormsAuthAd.Reports" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="reports-body">
<head runat="server">
<title>Reports</title>
<link href="../css/Style.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div class="params-container container">
<asp:TextBox ID="txtStart" runat="server" placeholder="From Date" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtEnd" runat="server" placeholder="To Date" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtBrand" runat="server" placeholder="Brand" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtSeason" runat="server" placeholder="Season" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtComp" runat="server" placeholder="Company" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtLoc" runat="server" placeholder="Location" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtLine" runat="server" placeholder="Line" class="input-fields"></asp:TextBox>
<asp:Button ID="btnShow" runat="server" OnClick="Button1_Click" Text="Generate" class="input-fields"/>
</div>
<div class="rpt-container container">
<rsweb:ReportViewer ID="rptVwr" runat="server" CssClass="rpt-viewer"></rsweb:ReportViewer>
</div>
</form>
</body>
</html>
CODE BEHIND
private void showReport()
{
rptVwr.Reset();
DataTable dt = GetData(txtStart.Text, txtEnd.Text, txtBrand.Text, txtSeason.Text, txtComp.Text, txtLoc.Text);
rptVwr.Visible = true;
ReportDataSource rds = new ReportDataSource("DataSet2", dt);
rptVwr.LocalReport.DataSources.Add(rds);
rptVwr.LocalReport.ReportPath = "../ReportServer/StockExport.rdl";
ReportParameter[] rptParams = new ReportParameter[]
{
new ReportParameter("StartDate",txtStart.Text),
new ReportParameter("EndDate",txtEnd.Text),
new ReportParameter("Brand",txtBrand.Text),
new ReportParameter("Season",txtSeason.Text),
new ReportParameter("Company",txtComp.Text),
new ReportParameter("Store",txtLoc.Text),
};
rptVwr.LocalReport.SetParameters(rptParams);
rptVwr.LocalReport.Refresh();
}
private DataTable GetData(string fromDate, string toDate, string brandCode, string seasonCode, string compCode, string locCode)
{
DataTable dt = new DataTable();
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings ["ReportServerConnStr"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("sp_valueEntryStock", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#StartDate", SqlDbType.NVarChar).Value = fromDate;
cmd.Parameters.Add("#EndDate", SqlDbType.NVarChar).Value = toDate;
cmd.Parameters.Add("#Season", SqlDbType.NVarChar).Value = seasonCode;
cmd.Parameters.Add("#Brand", SqlDbType.NVarChar).Value = brandCode;
cmd.Parameters.Add("#Company", SqlDbType.NVarChar).Value = compCode;
cmd.Parameters.Add("#Store", SqlDbType.NVarChar).Value = locCode;
cmd.CommandTimeout = 1000;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
return dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
showReport();
}
Obviously, I did not want a hard-coded number of textboxes so I tweaked my code to dynamically add textboxes on page load based on a table in Sql Server.Here is my existing code and screenshot:
Page after submitting parameters
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [FieldNum],[FieldName],[AspId],[SqlParameter] FROM [MIS_FieldsMaster]", con))
{
cmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dtable);
int i = 0;
foreach (DataRow dr in dtable.Rows)
{
TextBox tb = new TextBox();
tb.ID = dr["AspId"].ToString().Trim();
stringArray[i] = dr["SqlParameter"].ToString().Trim();
tb.Text = stringArray[i];
ph1.Controls.Add(tb);
i++;
}
}
}
}
private void showReport()
{
rptVwr.Reset();
DataTable dt = GetData();
rptVwr.Visible = true;
ReportDataSource rds = new ReportDataSource("DataSet2", dt);
rptVwr.LocalReport.DataSources.Add(rds);
rptVwr.LocalReport.ReportPath = "../ReportServer/StockExport.rdl";
rptVwr.LocalReport.Refresh();
}
private DataTable GetData()
{
DataTable dt = new DataTable();
int i = 0;
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["ReportServerConnStr"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("sp_valueEntryStock", cn);
cmd.CommandType = CommandType.StoredProcedure;
foreach (TextBox textBox in ph1.Controls.OfType<TextBox>())
{
cmd.Connection = cn;
cmd.Parameters.AddWithValue("#" + stringArray[i], textBox.Text);
i++;
}
cmd.CommandTimeout = 1000;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
return dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
showReport();
}
So it does not even show me any error message so I do not really know where to look. I debugged the new code and I believe it is retrieving the data in the stored procedure because the local variable shows rows retrieved under datatable dt. The only thing is the report does not show in the reportViewer. It does not even show report toolbars.
Row retrieved from datatable dt
I would greatly appreciate any help. Thanks.
I figured out the reason for the report not displaying in the reportviewer.
It seems that I still need to add the parameters and set it to the reportviewer, like in my first working code:
ReportParameter[] rptParams = new ReportParameter[]
{
new ReportParameter("StartDate",txtStart.Text),
new ReportParameter("EndDate",txtEnd.Text),
new ReportParameter("Brand",txtBrand.Text),
new ReportParameter("Season",txtSeason.Text),
new ReportParameter("Company",txtComp.Text),
new ReportParameter("Store",txtLoc.Text),
};
rptVwr.LocalReport.SetParameters(rptParams);
Obviously =, it still needs to be dynamic so here is the code that I used:
List<ReportParameter> paramList = new List<ReportParameter>();
int i = 0;
foreach (TextBox textBox in ph1.Controls.OfType<TextBox>())
{
paramList.Add(new ReportParameter(stringArray[i], textBox.Text));
i++;
}
rptVwr.LocalReport.SetParameters(paramList);
Now, I am able to generate the dynamic textboxes and at the same time pass the values in those textboxes to my sql server stored procedure and finally generate and display the report based on the same textboxes.
I would consider this solved, but I just have a niggling question in my head:
Why didn't my code work when it is exactly the same (at least logically if not syntactically) as the code in the youtube example that I took: Two way to pass parameter in stored procedure and display the output in Report Viewer using C#

Want to display list data in html table C#

enter image here
I want to add list data in the html Table.
The list data can be various, so table rows were dynamic and if List size increase user can use paging in table to move next...
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
Date1.Add(sdr["Date"].ToString());
Time.Add(sdr["Time"].ToString());
Event.Add(sdr["Event"].ToString());
Venue.Add(sdr["Venue"].ToString());
}
}
conn.Close();
}
}
for (int i = 0; i < Date1.Count; i++) {
string Date11 = Date1[i];
string Time1 = Time[i];
string Event1 = Event[i];
string Venue1 = Venue[i];
if(Venue1.Contains(country) || Venue1.Contains(Code[0]))
{
Result.Add( Date11 + " " + Time1 + " " + Event1 + " " + Venue1);
}
}
Can someone kindly give me code/hint which can i use in my Project. I will be very thankful to you.
The example below takes care of the following requirements which you've listed in the question:
Generates an HTML table containing your data
Has paging functionality
Supports dynamic columns
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
gvEvents.DataSource = this.GetEvents();
gvEvents.DataBind();
}
}
private DataTable GetEvents()
{
var table = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using(var connection = new SqlConnection(connectionString))
{
using(var command = new SqlCommand("SELECT TOP 100 Date,Time,Event,Venue FROM Event",connection))
{
connection.Open();
var adapter = new SqlDataAdapter(command);
adapter.Fill(table);
connection.Close();
}
}
int rows = table.Rows.Count;//Place breakpoint to make sure table has rows
return table;
}
protected void gvEvents_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvEvents.PageIndex = e.NewPageIndex;
gvEvents.DataSource = this.GetEvents();
gvEvents.DataBind();
}
.ASPX:
<form id="form1" runat="server">
<asp:GridView ID="gvEvents" runat="server" AllowPaging="true" PageSize="2" OnPageIndexChanging="gvEvents_PageIndexChanging">
</asp:GridView>
</form>
Output:

Gridview Search box in ASP.NET

I have made search box using textbox and button control to search the data in my GridView, for datasource I'm using ObjectDataSource. In ObjectDataSource Class I'm Using parameterized procedure to select data from database table, but the problem was occured here, ObjectDataSource expect a value for parameter class. I have solved this with hardcoded the class if it null give the parameter value equals to white space, it works good.
If there is another way solve this without hardcoded the class, any answers would be helpful, thanks
Here is my ObjectDataSource Select Class
public static List<T_Penerbit> GetSearchPenerbit(string Cari)
{
if (string.IsNullOrWhiteSpace(Cari))
{
Cari = " ";
}
List<T_Penerbit> listSearchPenerbit = new List<T_Penerbit>();
string cs = ConfigurationManager.ConnectionStrings["cs_perpustakaan"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetPenerbitBySearch", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramSearch = new SqlParameter("#parameter", Cari);
cmd.Parameters.Add(paramSearch);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
T_Penerbit penerbit = new T_Penerbit();
penerbit.ID = Convert.ToInt32(rdr["ID"]);
penerbit.Penerbit = rdr["Nama_Penerbit"].ToString();
penerbit.Kota = rdr["Kota"].ToString();
penerbit.Handphone = rdr["Handphone"].ToString();
penerbit.Email = rdr["Email"].ToString();
listSearchPenerbit.Add(penerbit);
}
}
return listSearchPenerbit;
}
And here is my button Search Click event
protected void ButtonKelolaDataPenerbitCariPenerbit_Click(object sender, EventArgs e)
{
ObjectDataSourceCariDataPenerbit.SelectParameters.Clear();
ObjectDataSourceCariDataPenerbit.SelectParameters.Add("Cari", TextBoxKelolaDataPenerbitCariPenerbit.Text);
ObjectDataSourceCariDataPenerbit.DataBind();
}
Presentation changes :
<div style="margin-top:50px">
SEARCHING
<br /><br />
Enter Id : -
<asp:TextBox ID="txtSearchId" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
</div>
Back-end updates :
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["StudDBConnectionString"].ToString());
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "select * from tbl_stud where id="+txtSearchId.Text;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
grvStudentWithoutDatasource.DataSource = dataTable;
grvStudentWithoutDatasource.DataBind();
}
Note: The given code is according to my database, Please change database column accordingly.
try this
aspx file:
<asp:ObjectDataSource runat="server" ID=" ObjectDataSourceCariDataPenerbit" TypeName="Penerbit" SelectMethod="GetSearchPenerbit">
<SelectParameters>
<asp:ControlParameter ControlID="TextBoxKelolaDataPenerbitCariPenerbit" Name="Cari" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
button Search Click event
protected void ButtonKelolaDataPenerbitCariPenerbit_Click(object sender, EventArgs e)
{
ObjectDataSourceCariDataPenerbit.DataBind();
}

What is the right way to populate a DropDownList from a database?

I am populating a DropDownList from a SQL Server database as shown below. It works fine, but I'm not sure it's a good way. Can someone shed some light on this method, and give some improvements?
private void LoadSubjects()
{
ddlSubjects.Items.Clear();
string selectSQL = "SELECT SubjectID,SubjectName FROM Students.dbo.Subjects";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
ListItem newItem = new ListItem();
newItem.Text = "<Select Subject>";
newItem.Value = "0";
ddlSubjects.Items.Add(newItem);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
newItem = new ListItem();
newItem.Text = reader["SubjectName"].ToString();
newItem.Value = reader["SubjectID"].ToString();
ddlSubjects.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
//TODO
}
finally
{
con.Close();
}
}
You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).
For example, if you wanted to use a DataTable:
ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
EDIT - More complete example
private void LoadSubjects()
{
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
adapter.Fill(subjects);
ddlSubject.DataSource = subjects;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
}
To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:
<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>
You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
from the code-behind, or you'll have two "" items.
I hope I am not overstating the obvious, but why not do it directly in the ASP side? Unless you are dynamically altering the SQL based on certain conditions in your program, you should avoid codebehind as much as possible.
You could do the above all in ASP directly without code using the SqlDataSource control and a property in your dropdownlist.
<asp:GridView ID="gvSubjects" runat="server" DataKeyNames="SubjectID" OnRowDataBound="GridView_RowDataBound" OnDataBound="GridView_DataBound">
<Columns>
<asp:TemplateField HeaderText="Subjects">
<ItemTemplate>
<asp:DropDownList ID="ddlSubjects" runat="server" DataSourceID="sdsSubjects" DataTextField="SubjectName" DataValueField="SubjectID">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsSubjects" runat="server"
SelectCommand="SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
public void getClientNameDropDowndata()
{
getConnection = Connection.SetConnection(); // to connect with data base Configure manager
string ClientName = "Select ClientName from Client ";
SqlCommand ClientNameCommand = new SqlCommand(ClientName, getConnection);
ClientNameCommand.CommandType = CommandType.Text;
SqlDataReader ClientNameData;
ClientNameData = ClientNameCommand.ExecuteReader();
if (ClientNameData.HasRows)
{
DropDownList_ClientName.DataSource = ClientNameData;
DropDownList_ClientName.DataValueField = "ClientName";
DropDownList_ClientName.DataTextField="ClientName";
DropDownList_ClientName.DataBind();
}
else
{
MessageBox.Show("No is found");
CloseConnection = new Connection();
CloseConnection.closeConnection(); // close the connection
}
}
((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;

Categories