I am making an application about article publication. I have 2 tables
"artikulli"
id int Unchecked
tema varchar(250) Checked
abstrakti text
data_publikimit date
path varchar(350)
keywords varchar(350)
kategoria_id int
departamenti_id int
"kategorite"
id int Unchecked
emertimi varchar(350)
I want to display in a dropdown list all values of field "emertimi" and when the user selects one value to save id of that value in table "artikulli".
I have done the following, but I have the problem with syntax because I am using DATALIST.
public partial class AddArticle : System.Web.UI.Page
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
try
{
if (!IsPostBack)
{
Bind();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
public void Bind()
{
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
protected void datalist2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
TextBox txtAbstrakti = e.Item.FindControl("txtAbstrakti") as TextBox;
TextBox txtData = e.Item.FindControl("txtData") as TextBox;
TextBox txtKeywords = e.Item.FindControl("txtKeywords") as TextBox;
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection conn = new SqlConnection(connection);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "Insert into artikulli(tema,abstrakti,data_publikimit,path,keywords,kategoria_id) values (#tema,#abstrakti,#data,#filename,#keywords,#kategoria)";
command.Parameters.Add(new SqlParameter("#tema", txtTema.Text));
command.Parameters.Add(new SqlParameter("#abstrakti", txtAbstrakti.Text));
command.Parameters.Add(new SqlParameter("#data", txtData.Text));
command.Parameters.Add(new SqlParameter("#keywords", txtKeywords.Text));
command.Parameters.Add(new SqlParameter("#kategoria", drpdKategoria.SelectedValue));
FileUpload FileUploadArtikull = (FileUpload)e.Item.FindControl("FileUploadArtikull");
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise se file qe lejohet eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
//add parameters
command.Parameters.AddWithValue("#filename", filename);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni ngarkuar asnje artikull');", true);
}
}
}
AddArtikull.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddArtikull.aspx.cs" Inherits="AddArticle" MasterPageFile="~/MasterPage2.master" %>
<asp:Content ID="content2" ContentPlaceholderID=ContentPlaceHolder2 runat="server">
<asp:DataList ID="datalist2" runat="server"
onitemcommand="datalist2_ItemCommand" >
<FooterTemplate>
<section id="main" class="column" runat="server" style="width:900px;">
<article class="module width_full" style="width:900px;">
<header><h3 style="text-align: center">Shto Artikull </h3></header>
<div id="Div1" class="module_content" runat="server">
<asp:Label ID="Label1" runat="server" style="font-weight: 700">Tema</asp:Label>
<fieldset>
<asp:TextBox ID="txtTema" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTema" runat="server"
ControlToValidate="txtTema" Display="Dynamic"
ErrorMessage="Kjo fushe eshte e nevojshme" style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset><br />
<asp:Label ID="Label6" runat="server" style="font-weight: 700">Abstrakti</asp:Label>
<fieldset>
<asp:TextBox ID="txtAbstrakti" style="height:250px;" Textmode="Multiline" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorAbstrakti" runat="server"
ControlToValidate="txtAbstrakti" ErrorMessage="Kjo fushe eshte e nevojshme"
style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset>
<asp:Label ID="lblData" runat="server" style="font-weight: 700">Data e Publikimit</asp:Label>
<fieldset>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox>
</fieldset>
<asp:Label ID="lblKeywords" runat="server" style="font-weight: 700">Keywords</asp:Label>
<fieldset>
<asp:TextBox ID="txtKeywords" runat="server"></asp:TextBox>
</fieldset>
<br />
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<div>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Insert"
/>
</div><br />
<strong>Ngarko Artikull</strong><br />
<asp:FileUpload ID="FileUploadArtikull" runat="server" /><br />
<br />
<asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />
</div>
</article>
</section>
</FooterTemplate>
</asp:DataList>
</asp:Content>
It shows this error:
Compiler Error Message: CS0103: The name 'e' does not exist in the
current context
In this line:
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
In your bind method you are calling an object e that doesn't exist. If the dropdownlist isn't inside a bound element, you can just reference the front code directly, e.g.
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
without finding the control as long as it is runat="server"
UPDATE
Okay, so you need to add an OnItemCreated event in your datalist
OnItemCreated="datalist2_OnItemCreated"
Then in that method you need this
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
That will work for if you only have the footer, if you add an itemtemplate then you just need to get rid of the check for the footer and on each item creation grab that dropdownlist for that item
Related
Here in my code i'm trying to let the user edit the gridview and hence update the database accordingly.The gridview is made on a webform page in aspx which shows the user data in tabular structure.But the problem is here that when i click on edit link of gridview it lets me to edit the data but when i update the gridview row,the associated event of onrowupdating doesn't gets called or fired at all.Even when i written all the code for it but still it's not working.What's the problem in this Please help me with this.Below is my whole code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication5.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Welcome To My First Web Form<br />
<h1> Candidate Registration Form</h1>
<br />
<br />
Applicant's Name:
<asp:TextBox ID="TextBox1" runat="server" CausesValidation="True" EnableViewState="False" ValidateRequestMode="Enabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Please enter Your Name!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Applicant's FName"></asp:Label>
:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" ErrorMessage="Please enter your Father name!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Gender"></asp:Label>: <asp:RadioButtonList ID="gender" RepeatDirection="Horizontal" runat="server" Width="141px" RepeatLayout="Flow">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="gender" ErrorMessage="Please Choose your Gender" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="E-mail ID"></asp:Label>
:
<asp:TextBox ID="TextBox3" runat="server" OnTextChanged="TextBox3_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox3" Display="Dynamic" ErrorMessage="E-mail address is required">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox3" Display="Dynamic" ErrorMessage="E-mail addresses must be in the format of name#domain.xyz" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ForeColor="Red">Invalid Format</asp:RegularExpressionValidator>
<br />
<br />
<asp:Label ID="Label4" runat="server" Text="password"></asp:Label>
:
<asp:TextBox ID="TextBox4" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="TextBox4" Display="Dynamic" ErrorMessage="Password is Required!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label5" runat="server" Text="Confirm Password"></asp:Label>
:
<asp:TextBox ID="TextBox5" runat="server" TextMode="Password"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox5" ErrorMessage="The passwords Didn't Match!" ForeColor="Red" ControlToCompare="TextBox4" Display="Dynamic"></asp:CompareValidator>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
<br />
<asp:GridView ID="GridView1" runat="server"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating1">
<%-- <Columns>
<asp:BoundField DataField="Cname" />
<asp:BoundField DataField="Cfname" />
<asp:BoundField DataField="Cmail" />
</Columns>--%>
</asp:GridView>
<br />
<br />
</div>
</form>
</body>
</html>
CS code file for this:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication5
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\admin\documents\visual studio 2013\Projects\WebApplication5\WebApplication5\App_Data\Candidates.mdf;Integrated Security=True");
public static int count = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
gvbind();
//DataTable dt = new DataTable();
//dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Name"), new DataColumn("FatherName"), new DataColumn("E-mail") });
//ViewState["Candidates"] = dt;
//GridView1.DataSource = (DataTable)ViewState["Candidates"];
//GridView1.DataBind();
}
}
protected void gvbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Candidates", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void TextBox3_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
count += 1;
int rowIndex = 0;
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Candidates values('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
//if (count > 1)
//{
// DataTable dtCurrentTable = (DataTable)ViewState["Candidates"];
// DataRow drCurrentRow = null;
// if (dtCurrentTable.Rows.Count > 0) {
// //for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
// //{
// drCurrentRow = dtCurrentTable.NewRow();
// int totalrows = dtCurrentTable.Rows.Count;
// dtCurrentTable.Rows.Add(drCurrentRow);
// dtCurrentTable.Rows[totalrows]["Name"] = TextBox1.Text;
// dtCurrentTable.Rows[totalrows]["FatherName"] = TextBox2.Text;
// dtCurrentTable.Rows[totalrows]["E-mail"] = TextBox3.Text;
// rowIndex++;
// //}
// ViewState["Candidates"] = dtCurrentTable;
// GridView1.DataSource = dtCurrentTable;
// GridView1.DataBind();
// TextBox1.Text = string.Empty;
// TextBox2.Text = string.Empty;
// TextBox3.Text = string.Empty;
// }
//}
//else
//{
// DataTable dt = (DataTable)ViewState["Candidates"];
// dt.Rows.Add(TextBox1.Text.Trim(), TextBox2.Text.Trim(), TextBox3.Text.Trim());
// ViewState["Candidates"] = dt;
// TextBox1.Text = string.Empty;
// TextBox2.Text = string.Empty;
// TextBox3.Text = string.Empty;
// BindGrid();
//}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
//protected void BindGrid()
//{
// //GridView1.DataSource = (DataTable)ViewState["Candidates"];
// //GridView1.DataBind();
//}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
gvbind();
}
protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
string name = GridView1.SelectedRow.Cells[0].Text;
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
TextBox textName = (TextBox)row.Cells[0].Controls[0];
TextBox textFname = (TextBox)row.Cells[1].Controls[0];
TextBox texte = (TextBox)row.Cells[2].Controls[0];
////TextBox textadd = (TextBox)row.FindControl("txtadd");
////TextBox textc = (TextBox)row.FindControl("txtc");
GridView1.EditIndex = -1;
con.Open();
SqlCommand cmd = new SqlCommand("update Candidates set Cname='" + textName.Text + "',Cfname='" + textFname.Text + "',Cmail='" + texte.Text + "'where Cname='" + name + "'", con);
cmd.ExecuteNonQuery();
con.Close();
gvbind();
//GridView1.DataBind();
}
}
}
I have a listboxitems i want that when i select value then page redirect to other page.I use onSelectedIndex property event function but it's not working.I search on google alot i find many solutions like autopostback property='true'. I apply all solutions but still not working.My listbox values coming from database and it load fine but page not redirecting to other page.
Here is my code aspx code:
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<div class="select-db">
<form runat="server"></form>
<label style="position:relative; font-weight:bold;bottom:230px; left:450px; color:White;">Select Database</label>
<asp:ListBox ID="ListBox1" runat="server" Height="202px" Width="262px"
style="margin-left: 247px; margin-top: 68px"
onselectedindexchanged="ListBox_Changed" AutoPostBack="true" EnableViewState="True" >
</asp:ListBox>
</div>
</asp:Content>
and here is my aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
getdata();
}
}
public void getdata()
{
string user = Session["name"].ToString();
SqlConnection cnn = new SqlConnection("Data Source=HAMEED_KHAN\\SQLEXPRESS;Initial Catalog=db_compiler;Integrated Security=True");
SqlCommand cmd2 = new SqlCommand("SELECT User_ID from tbl_user WHERE User_Name='" + user + "'", cnn);
cnn.Open();
string id = cmd2.ExecuteScalar().ToString();
int ID = Int32.Parse(id);
SqlCommand cmd = new SqlCommand("USE db_compiler SELECT Database_Name FROM Create_db WHERE User_ID='" + ID + "'", cnn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
string value = row["Database_Name"] + "";
ListBox1.Items.Add(value);
}
}
}
public void ListBox_Changed(object sender, EventArgs e)
{
Session["value"] = ListBox1.SelectedValue;
Response.Redirect("CreateTable.aspx");
}
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
}
I also use 'breakpoint' to check that event is firing or not but event is not firing.I don't know why?????
All asp.net controls have to be inside a <form> that has a runat="server" attribute. Move the closing tag of your form to the end of the content and it should work. Like this:
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<div class="select-db">
<form runat="server">
<label style="position:relative; font-weight:bold;bottom:230px; left:450px; color:White;">Select Database</label>
<asp:ListBox ID="ListBox1" runat="server" Height="202px" Width="262px" style="margin-left: 247px; margin-top: 68px" OnSelectedIndexChanged="ListBox_Changed" AutoPostBack="true" EnableViewState="True" >
</asp:ListBox>
</form>
</div>
</asp:Content>
Also remember you can only have one <form> with runat="server".
hi i tried to display image from sql table to gridview but its not displaying this is my code to bind gridview with sql table records.....
When the user login , the user login photo should display thats y i am trying
the image already stored in database but there is an ISSUE to retrive the image from database to gridview
PostBookChat.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblsession.Text = "Welcome" + Convert.ToString(Session["UName"]);
sessionimage();
}
}
private void sessionimage()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
try
{
int EmpID = (int)Session["EmpID"];
SqlDataAdapter Adp = new SqlDataAdapter("select EmpID,Photo from TBL_PBLogin where EmpID='" + EmpID + "'", con);
DataTable Dt = new DataTable();
con.Open();
Adp.Fill(Dt);
gridviewphoto.DataSource = Dt;
gridviewphoto.DataBind();
con.Close();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
PostBookChat.aspx
<body>
<form id="form1" runat="server">
<div>
<div id="header">
<img src="Image/book.png" height="60" width="140" style ="margin-left:0px;float:left;"/>
<div id="login">
<b><asp:Label ID="lblsession" runat="server" ForeColor="white" CssClass="label"></asp:Label>
<asp:GridView ID="gridviewphoto" runat="server" AutoGenerateColumns="false" BackColor="#CC3300" ForeColor="Black" ShowHeader="false" GridLines="None">
<Columns>
<asp:TemplateField ControlStyle-Width="100" ControlStyle-Height="100">
<ItemTemplate>
<asp:Image ID="Image" runat="server" ImageUrl='<%# "~/Handler.ashx?id=" + Eval("EmpID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnlogout" runat="server" Text="Sign Out" CssClass="myButton" OnClick="btnlogout_Click"/>
</div>
</div>
</body>
Handler.ashx
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["EmpID"] == null) return;
string connStr = ConfigurationManager.AppSettings["connect"].ToString();
string pictureId = context.Request.QueryString["EmpID"];
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Photo FROm TBL_PBLogin WHERE EmpID = #EmpId", conn))
{
cmd.Parameters.Add(new SqlParameter("#EmpID", pictureId));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.ContentType = "image/png";
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("Photo")]);
reader.Close();
}
}
}
}
DataBase
EmpID (PK,int notnull) (1,1)
UName(varchar(255),notnull)
Password(varchar(255),notnull)
Photo(image,null)
I am trying to get two text boxes to populate when a drop down list has it's value selected (and I want the data in the text boxes to change when the selection is changed without the page reloading), I wrote some code compiling what I have gathered from other questions like this, but for some reason its just not working here is my CS.
public partial class UsersFormPage : Page
{
protected void userddlistedit_SelectedIndexChanged(object sender, EventArgs e)
{
FillBoxes(userddlistedit.SelectedValue);
}
private void FillBoxes(string HR_ID)
{
// Create a new dataset object
DataSet dt = new DataSet();
// Create SqlConnection
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=SQL2008R2SRV;Initial Catalog=employeetrainingtracking;Integrated Security=True";
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
// Set the connection on the sql command object
cmd.Connection = conn;
cmd.CommandText = "select * from users where HR_ID='" + HR_ID + "'";
using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
{
adap.Fill(dt);
}
}
}
if (dt.Tables[0].Rows.Count > 0)
{
usernameedit.Text = dt.Tables[0].Rows[0]["Username"].ToString(); //Where column name us the Fields for your Table that you wanted to display in the TextBoxes
passwordedit.Text = dt.Tables[0].Rows[0]["Password"].ToString();
}
}
}
And here is the part of my page it affects:
<li class="form-row text-row">
<label>User:</label>
<asp:DropDownList ID="userddlistedit" runat="server" CssClass="text-input-dds" DataSourceID="personnelsql" DataTextField="HR_ID" DataValueField="HR_ID" AutoPostBack="True" OnSelectedIndexChanged="userddlistedit_SelectedIndexChanged" />
</li>
<li class="form-row text-input-row">
<label>Username:</label>
<asp:TextBox name="usernameedit" type="text" class="text-input-lg required" id="usernameedit" runat="server" AutoPostBack="True" />
</li>
<li class="form-row text-input-row">
<label>Password:</label>
<asp:TextBox name="passwordedit" type="text" class="text-input-lg required" id="passwordedit" runat="server" AutoPostBack="True" />
</li>
I cannot seem to figure out why its not working.
This is the data source for my drop down list:
<asp:SqlDataSource ID="personnelsql" runat="server"
ConnectionString="<%$ ConnectionStrings:employeetrainingtrackingConnectionString %>"
SelectCommand="SELECT * FROM personnel ORDER BY HR_ID">
</asp:SqlDataSource>
I figured out what I was missing, so I am posting the code below so people can use it:
Here is the code that goes on the CS page:
protected void userddlistedit_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM users ";
selectSQL += "WHERE HR_ID='" + userddlistedit.SelectedItem.Value + "'";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
usernameedit.Text = reader["Username"].ToString();
passwordedit.Text = reader["Password"].ToString();
accessleveledit.SelectedValue = reader["AccessLevel"].ToString();
reader.Close();
lblResults.Text = "";
}
finally
{
con.Close();
}
}
This is the code in the actual aspx page, I added two things:
-I added the DropDownExtender
-I added the triggers (after the but before the tag
<li class="form-row text-row">
<label>User:</label>
<asp:DropDownList ID="userddlistedit" runat="server" CssClass="text-input-dds" AutoPostBack="True" OnSelectedIndexChanged="userddlistedit_SelectedIndexChanged"></asp:DropDownList>
</li>
<li class="form-row text-input-row">
<label>Username:</label>
<asp:TextBox name="usernameedit" type="text" class="text-input-lg required" id="usernameedit" runat="server"></asp:TextBox>
<asp:DropDownExtender ID="ExtenderUserEdit" DropDownControlID="userddlistedit" Enabled="true" TargetControlID="usernameedit" runat="server"></asp:DropDownExtender>
<asp:RequiredFieldValidator runat="server" ID="ValidateUsernameEdit" ControlToValidate="usernameedit" ErrorMessage="Username is required" Display="dynamic" ValidationGroup="EditSection">*</asp:RequiredFieldValidator>
</li>
<li class="form-row text-input-row">
<label>Password:</label>
<asp:TextBox name="passwordedit" type="text" class="text-input-lg required" id="passwordedit" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="ValidatePasswordEdit" ControlToValidate="passwordedit" ErrorMessage="Password is required" Display="dynamic" ValidationGroup="EditSection">*</asp:RequiredFieldValidator>
</li>
.....
<Triggers>
<asp:AsyncPostBackTrigger ControlID="userddlistedit" EventName="SelectedIndexChanged" />
</Triggers>
I also changed the way I got my data for the drop down list to the following (added in the CS page):
private void UsersListDD()
{
userddlist.Items.Clear();
userddlistedit.Items.Clear();
userddlistdelete.Items.Clear();
string selectSQL = "SELECT * FROM personnel";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["FirstName"] + " " + reader["LastName"];
newItem.Value = reader["HR_ID"].ToString();
userddlist.Items.Add(newItem);
userddlistedit.Items.Add(newItem);
userddlistdelete.Items.Add(newItem);
}
reader.Close();
}
finally
{
con.Close();
}
}
Hopefully, this helps someone.
I have a repeater which displays 'News' on home page which is diplayed from database. I want to display just 2records at a time and automatically scrolling next two items after certain milliseconds with scrolling or fadein-fadeout effect.
In aspx page:
<asp:Repeater ID="RepDetails" runat="server" OnItemDataBound="RepDetails_ItemDataBound">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<div id="MainContent" style="border: 1px;">
<table>
<tr>
<td rowspan="2" class="auto-style2">
<img src="Images/lasts1.png" />
</td>
<td>
<asp:Label ID="lblNewsTitle" runat="server" Font-Bold="True" /></td>
<td> </td>
</tr>
<tr width="100px">
<td>
<asp:Label ID="lblNewsDescription" runat="server" /></td>
<td> </td>
</tr>
</table>
</div>
<hr />
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
In .cs Page:
protected void RepDetails_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView dr = e.Item.DataItem as DataRowView;
string Id = Convert.ToString(dr["NewsID"]);
//HtmlGenericControl teammemberapp = e.Item.FindControl("teammemberapp") as HtmlGenericControl;
//Link to TeamMemberDetails Page
//teammemberapp.Attributes.Add("onclick", "window.location.href='NewsDetails.aspx?Id=" + Id + "'");
string newsTitle = Convert.ToString(dr["NewsTitle"]);
Label lblNewsDescription = e.Item.FindControl("lblNewsDescription") as Label;
Label lblNewsTitle = e.Item.FindControl("lblNewsTitle") as Label;
//set First Name Label
lblNewsTitle.Text = newsTitle;
string newsDescription = Convert.ToString(dr["NewsDescription"]);
if (newsDescription.Length > 50)
{
lblNewsDescription.Text = newsDescription.Substring(0, 50) + "..";
}
else
{
lblNewsDescription.Text = newsDescription;
}
}
}
public void GetRecord()
{
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString.ToString();
DataTable datatable = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
connection.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_NewsSelectYES";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(datatable);
connection.Close();
}
//Bind Table to Repeater
RepDetails.DataSource = datatable;
RepDetails.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Get all news with yes
GetRecord();
}
}
Help Appreciated!
Thanks!
Try to use some kind of jquery slider