asp DropDownList always select 0 index with postback check - asp.net

i have aspx and aspx.cs files when i try to get the selected item of the
DropDownList
it always get the item at 0 index
<div style="text-align:center">
<b>Scegliere il nome del report * </b>
<asp:DropDownList id="dropdownlist1" style="width:250px;" runat="server"></asp:DropDownList>
<br />
<br />
<br />
<b>Scegliere la data del report </b>
<asp:TextBox runat="server" ID="txtSchedDate" name="txtSchedDate" type="text" cssclass="datebox" style="height:20px;" ReadOnly="true"/>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Pubblica" OnClientClick="" OnClick="Button1_Click" />
<br />
<br />
<br />
<br />
<asp:Label ID="Label1" Font-Names="Arial" Font-Size="15px" runat="server" ForeColor="Red" Font-Bold="True" Text=""></asp:Label>
<div id="divUpload" style="display:none">
<div style="width:200pt;;text-align:center;">Pubblicando...</div>
</div>
</div>
the c# code
protected double size = 1;
private string connectionString;
private OracleConnection connection;
private OracleCommand processNumQuery;
private int indexdropitem;
protected void Page_Load(object sender, EventArgs e)
{
if (Request["CONNECTSTRING"] == null && Session["CONNECTSTRING"] == null)
{
Response.Redirect("sessionup.asp?type=Pubreport");
}
else
{
if (Request["CONNECTSTRING"] != null)
{
connectionString = Request["CONNECTSTRING"].ToString();
}
else
{
connectionString = Session["CONNECTSTRING"].ToString();
}
if (connectionString.IndexOf("DSN=") >= 0)
{
Utility util = new Utility();
connectionString = util.ConnStr(connectionString);
}
Session["CONNECTSTRING"] = connectionString;
connection = new OracleConnection(connectionString);
connection.Open();
}
if (!IsPostBack)
{
processNumQuery = new OracleCommand("select distinct nome_report from rpg_notification",connection);
OracleDataReader reader = processNumQuery.ExecuteReader();
while (reader.Read())
{
dropdownlist1.Items.Insert(0, new ListItem(reader.GetString(0), ""));
}
reader.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("try :" + dropdownlist1.SelectedIndex + " - " + txtSchedDate.Text + " - " + dropdownlist1.Items[dropdownlist1.SelectedIndex].Text + " - " + Request["txtSchedDate"] + " - ");
}
i awalys get the 0 index please what i have to do??

ASP.NET is not "smart" enough to pass the actual selected index of submitted drop down list. Instead, it depends on the browser sending the selected value, then depending on the items having different value.
If there are items with the same value and one of them is selected, the server side SelectedIndex will return the index of the first item having that value. I have just created a quick test and was proven right. (not familiar with any .NET fiddle, sorry)
In your specific case, all items had empty value due to that line:
dropdownlist1.Items.Insert(0, new ListItem(reader.GetString(0), ""));
To "fix" your problem just add a value:
string myValue = reader.GetString(0);
dropdownlist1.Items.Insert(0, new ListItem(myValue, myValue));

that should work...just for debuging proposes, try to call dropdownlist1.SelectedItem.Text instead of dropdownlist1.Items[dropdownlist1.SelectedIndex].Text and see what you get

Related

ASP.net gridview cant update image

So i'm a newbie in asp.net. I have this college project which need to use update function. I made the update function, its work fine for all columns except for picture's column. Its not updating picture database, and show the previous picture in the gridview. The pictures in the folder already updated but the gridview just show the previous picture (not the updated one). I need your help please thank you :)
this is the gridview aspx code, if update button was clicked, it will redirect to another page.
<div>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Images" ItemStyle-Height="50px" ItemStyle-Width="50px" >
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("pic") %>'/>/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="nama" HeaderText="nama" />
<asp:BoundField DataField="harga" HeaderText="harga" />
<asp:BoundField DataField="stok" HeaderText="stok" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update" wID='<%# Eval("Id") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
this is the Page_Load function
public List<Table> getAll()
{
List<Table> watches = (from x in de.Tables select x).ToList();
return watches;
}
public void loadData()
{
GridView1.DataSource = repo.getAll();
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) loadData();
}
and redirected to update aspx
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:FileUpload ID="pic" runat="server" />
<br />
<asp:TextBox ID="name" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="price" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="stok" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Button" OnClick="btnUpdate_Click" />
This is the update function of btnUpdate in update aspx
protected void btnUpdate_Click(object sender, EventArgs e)
{
string ext = System.IO.Path.GetExtension(pic.FileName);
string nama = name.Text;
int harga = Int32.Parse(price.Text);
int stock = Int32.Parse(stok.Text);
Table update = (Table)Session["updateWatch"];
string pict = "..\\Pictures\\Watch Pictures\\" + update.Id + ext;
bool updateStatus = repo.update(update.Id, pict, nama, harga, stock);
if (updateStatus == false) Label1.Text = "fail";
else
{
string subPic = update.pic.Substring(3);
string path = Server.MapPath("~") + subPic;
string savepath = Server.MapPath("~/Pictures/Watch Pictures/");
System.IO.File.Delete(path);
pic.SaveAs(savepath + update.Id + ext);
Response.Redirect("WebForm1.aspx");
}
}
this is the update function in repository
public bool update(int id, string pic, string nama, int harga, int stok)
{
Table updateW = (from x in de.Tables where x.Id == id select x).FirstOrDefault();
updateW.pic = pic;
updateW.nama = nama;
updateW.harga = harga;
updateW.stok = stok;
de.SaveChanges();
if (updateW == null) return false;
return true;
}
this is the code for gridview datasource
public List<Table> getAll()
{
List<Table> watches = (from x in de.Tables select x).ToList();
return watches;
}

how to store data into database using text-area

How to store data in the database.
it will show the following exception
Additional information: Procedure or function 'spUploadImage' expects parameter '#detail', which was not supplied.
Following is the Movies.aspx file contents :
<html>
<head>
<script>
var maxAmount = 250;
function textCounter(textField, showCountField) {
if (textField.value.length > maxAmount) {
textField.value = textField.value.substring(0, maxAmount);
} else {
showCountField.value = maxAmount - textField.value.length;
}
}
</script>
</head>
<body>
<center>
<asp:Label ID="label3" Text="Name of Movie: " runat="server"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /><br />
<asp:Label ID="label4" Text="Details of Movie: " runat="server"></asp:Label><br />
<textarea id="txtCommentBox" name="txtCommentBox" rows="6" style="width:340px;" onKeyDown="textCounter(this.form.txtCommentBox,this.form.countDisplay);" onKeyUp="textCounter(this.form.txtCommentBox,this.form.countDisplay);"></textarea>
<br />
<input readonly type="text" name="countDisplay" size="3" maxlength="3" value="250"> Characters Remaining
<br />
<br />
<asp:Label ID="label2" Text="Select Image of Movie: " runat="server"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:HyperLink ID="HyperLink1" runat="server">View Uploaded Image</asp:HyperLink>
</center>
</body>
</html>
</asp:Content>
Following is the Movies.aspx.cs file contents :
public partial class Movies : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Label1.Visible = false;
HyperLink1.Visible = false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string txt = TextBox1.Text;
string text = Request.Form["txtCommentBox_1"];
HttpPostedFile postedFile= FileUpload1.PostedFile;
string fileName = Path.GetFileName(postedFile.FileName);
string fileExtension = Path.GetExtension(fileName);
int fileSize = postedFile.ContentLength;
if(fileExtension.ToLower()==".jpg" || fileExtension.ToLower()==".png" || fileExtension.ToLower()==".bmp" || fileExtension.ToLower()==".gif")
{
Stream stream= postedFile.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con=new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spUploadImage",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramName = new SqlParameter()
{
ParameterName = "#Name",
Value = fileName
};
cmd.Parameters.Add(paramName);
SqlParameter paramSize = new SqlParameter()
{
ParameterName = "#Size",
Value = fileSize
};
cmd.Parameters.Add(paramSize);
SqlParameter parammName = new SqlParameter()
{
ParameterName = "#mName",
Value = txt
};
cmd.Parameters.Add(parammName);
SqlParameter paramImageData = new SqlParameter()
{
ParameterName = "#ImageData",
Value = bytes
};
cmd.Parameters.Add(paramImageData);
SqlParameter paramdetail = new SqlParameter()
{
ParameterName = "#detail",
Value = text
};
cmd.Parameters.Add(paramdetail);
SqlParameter paramNewId = new SqlParameter()
{
ParameterName = "#NewId",
Value = -1,
Direction=ParameterDirection.Output
};
cmd.Parameters.Add(paramNewId);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Upload Successful";
Label1.ForeColor = System.Drawing.Color.Green;
HyperLink1.Visible = true;
HyperLink1.NavigateUrl = "~/Moviesimg.aspx?Id="+cmd.Parameters["#NewId"].Value.ToString();
}
}
else
{
Label1.Visible = true;
Label1.Text = "Only Images (.jpg, .png, .gif and .bmp) can be uploaded...";
Label1.ForeColor = System.Drawing.Color.Red;
HyperLink1.Visible = false;
}
}
}
and the stored procedure is as follows :
create proc spUploadImage
#Name nvarchar(255),
#Size int,
#ImageData varbinary(max),
#mName nvarchar(50),
#detail nvarchar(300),
#NewId int output
as
Begin
Insert into tblImages
values(#Name,#Size,#mName,#detail,#ImageData)
select #NewId = SCOPE_IDENTITY()
End
But I want to get a text from the text area and to store in the database.
but it raises an exception...
You are missing a form tag. Use an ASP control instead of a plain HTML control - all the other controls are ASP so be consistent.
<html>
<body>
<form id="form1" runat="server">
<asp:TextBox id="txtImagename1" TextMode="multiline" Columns="50"
Rows="1" runat="server" />
</form>
</body>
</html>
protected void Button1_Click(object sender, EventArgs e)
{
string text = Server.HtmlEncode(txtImagename1.Text);
...
}
The Request.Form collection cannot be used if your form is over 100 KB:
msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx
If you are setting runat="server" to any control, in that case the control must be placed inside a form tag with runat="server" like following
<html>
<body>
<form id="form1" runat="server">
<center>
<textarea id="txtImagename1" name="txtImagename1" runat="server" rows="1" cols="50">
</textarea>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:HyperLink ID="HyperLink1" runat="server">View Uploaded Image</asp:HyperLink>
</center>
</form>
</body>
</html>
To access this on server side you can simply use the the InnerText property of the TextArea as following.
txtImagename1.InnerText
If you want you can also access it using Form object also as following.
Request.Form["txtImagename1"]
For this the control can be simple TextArea without runat attribute.

DropDownList SelectIndexChanged not working?

This seems to be a common problem. I have tried different solutions but its still not working. This is my code.
HTML:
<div class="form-group">
<label for="exampleInputEmail1">Artist *</label>
<asp:DropDownList ID="artistDropdown" runat="server" CssClass="form-control" AutoPostBack="True" OnSelectedIndexChanged="artistDropdown_SelectedIndexChanged" ViewStateMode="Enabled"></asp:DropDownList>
<asp:TextBox ID="mytest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="artistDropdown" SetFocusOnError="true" ErrorMessage="Required Field" Font-Bold="True" Font-Names="Arial" Font-Size="X-Small" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:Label ID="lblMessage" runat="server" CssClass="help-block" Visible="False">Cant select Artist with no Manager</asp:Label>
</div>
Function: OnSelectedIndexChanged
protected void artistDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedArtist = artistDropdown.SelectedValue;
mytest.Text = selectedArtist;
string query = "Select [Manager ID] from Artist Where ID = '" + selectedArtist + "'";
string myConnection = dbController.connectionString;
SqlConnection conn = new SqlConnection(myConnection);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
object obj = cmd.ExecuteScalar();
if (obj is System.DBNull)
{
artistDropdown.SelectedValue = "";
lblMessage.Visible = true;
}
else
{
lblMessage.Visible = false;
}
conn.Close();
}
I am loading DropDownList in Page_Load() function and AutoPostBack="True" is set for DropDownList.
I have also made a TextBox which is being set to the selectedValue from DropDownList to check if on OnSelectedIndexChanged is firing. But text box remains empty.
What am I doing wrong?
Did you put the binding of your dropdown in the if (!postback) {} ?
If you rebind the list after every postback, you get the value of the first list item when you reach the artistDropdown_SelectedIndexChanged event.
If this item has an empty string value...

ASP.Net dropdown always return first value on button click event

I am trying to save value from a simple asp.net form.
I have few controls on the page like drop-down & text-box's
I fill the first drop-down on page load with Language & trigger post-bask on same to fill the second drop-down ddCategoryType which it fills with correct values based on the language selected, but problem is when i try to get the value on button click event value for ddCategoryType.SelectedItem.Value always return 0 for some reason which i am not able figure out right now
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddSelectLanguage.Items.Clear();
ddSelectLanguage.DataSource = DataProvider.GetLanguages();
ddSelectLanguage.DataBind();
ddSelectLanguage.Items.Insert(0, new ListItem("Select Language", "0"));
}
else
{
ddCategoryType.Items.Clear();
String strSql = "SELECT TypeName, TypeID FROM CategoryType WHERE LangID =" + ddSelectLanguage.SelectedItem.Value.ToString();
DataSet ds = new DataSet();
ds = DataProvider.Connect_Select(strSql);
ddCategoryType.DataSource = ds;
ddCategoryType.DataBind();
ddCategoryType.Items.Insert(0, new ListItem("Select Type", "0"));
}
}
protected void btnSaveCategory_Click(object sender, EventArgs e)
{
objArtCat.LanguageID = int.Parse(ddSelectLanguage.SelectedItem.Value.ToString());
objArtCat.CategoryName = txtCategoryName.Text;
objArtCat.CategoryType = int.Parse(ddCategoryType.SelectedItem.Value.ToString());
objArtCat.CategoryActive = bool.Parse(ddCategoryActive.SelectedItem.Value.ToString());
try
{
//bool result;
//result = objBLAddArticleCategory.CreateNewArticleCategory(objArtCat);
//if (result == true)
//{
// Response.Redirect("PageMessage.aspx?msg='Category has been Create Successfully'", true);
//}
//else
//{
//}
}
catch (Exception)
{ }
}
SAMPLE .ASPX CODE
<div class="row"></div>
<div class="row">
<asp:Label ID="lblSelectLang" CssClass="txtLabel" Text="Select Language :" runat="server" ></asp:Label>
<asp:DropDownList ID="ddSelectLanguage" runat="server" CssClass="ddGeneral"
DataTextField="LangName" DataValueField="LangID" CausesValidation="True"
AutoPostBack="True" >
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvddLanguage" runat="server" ErrorMessage="Please Select Language" ControlToValidate="ddSelectLanguage"
InitialValue="Select Language" ValidationGroup="atpAddNewArticle" ></asp:RequiredFieldValidator>
</div>
<div class="row">
<asp:Label ID="lblCategoryName" CssClass="txtLabel" runat="server" Text="Category Name :"></asp:Label>
<asp:TextBox ID="txtCategoryName" runat="server" CssClass="txtbox300"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFVtxtAuthorName" runat="server" ErrorMessage="*"
ControlToValidate="txtCategoryName" ValidationGroup="atpAddNewArticle" CssClass="validation"></asp:RequiredFieldValidator>
</div>
<div class="row">
<asp:Label ID="lblCategoryType" CssClass="txtLabel" runat="server" Text="Category Type :"></asp:Label>
<asp:DropDownList ID="ddCategoryType" runat="server" CssClass="ddGeneral" DataTextField="TypeName" DataValueField="TypeID" >
</asp:DropDownList>
</div>
<div class="row">
<asp:Label ID="lblCategoryActive" CssClass="txtLabel" runat="server" Text="Category Active :"></asp:Label>
<asp:DropDownList ID="ddCategoryActive" runat="server" CssClass="ddGeneral" >
<asp:ListItem Value="False" Selected="True">NO</asp:ListItem>
<asp:ListItem Value="True">YES</asp:ListItem>
</asp:DropDownList>
</div>
<div class="rowButton">
</br>
<asp:Button ID="btnUpdateArticle" runat="server" Text="Save Category" CssClass="btn" ValidationGroup="atpAddNewArticle" onclick="btnSaveCategory_Click" /> <input id="Reset" type="reset" class="btn" value="Reset" />
</div>
OutPut for ddCategoryType after postback
<div class="row">
<span class="txtLabel" id="MainContent_lblCategoryType">Category Type :</span>
<select class="ddGeneral" id="MainContent_ddCategoryType" name="ctl00$MainContent$ddCategoryType">
<option value="0" selected="selected">Select Type</option>
<option value="1">Article</option>
<option value="2">News</option>
<option value="3">Sports</option>
<option value="4">People</option>
<option value="5">Message</option>
</select>
</div>
In your Page_Load you are clearing the contents of ddCategoryType and therefore the SelectedIndex is reset to 0.
Remember that the Page_Load is always called, and it happens BEFORE the Button_Click event.
There are a few ways to handle this, for instance: don't perform all the code in your Page_Load's else clause if the SelectedIndex >= 0
Since you want to populate ddCategoryType based on a selected value from ddSelectLanguage, then populate the DDL based on that interaction, not in the Page_Load.
protected void Page_Load(object sender, EventArgs e)
{
ddSelectLanguage.SelectedIndexChanged += new
EventHandler(ddSelectLanguage_SelectedIndexChanged);
if (!IsPostBack)
{
ddSelectLanguage.Items.Clear();
ddSelectLanguage.DataSource = DataProvider.GetLanguages();
ddSelectLanguage.DataBind();
ddSelectLanguage.Items.Insert(0, new ListItem("Select Language", "0"));
}
}
Then
void ddSelectLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
ddCategoryType.Items.Clear();
String strSql = "SELECT TypeName, TypeID FROM CategoryType WHERE LangID =" + ddSelectLanguage.SelectedItem.Value.ToString();
DataSet ds = new DataSet();
ds = DataProvider.Connect_Select(strSql);
ddCategoryType.DataSource = ds;
ddCategoryType.DataBind();
ddCategoryType.Items.Insert(0, new ListItem("Select Type", "0"));
}
also, make your query take parameters.

Should this be a bug or not - ASP.NET Request parameter

I posted a number of bugs on Microsoft site and while they were real bugs, MSFT will close it as design [And I figured most people favour MSFT anyways]. Here is one that I am sure they will clasify as by design but to me this is a serious bug.
This is all I have in ASPX page (NET 3.5).
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" /><br />
<asp:Label ID="lblOutput" runat="server" Text="Label"></asp:Label>
Codebehind
protected void Page_Load(object sender, EventArgs e)
{ /* this works */
if (IsPostBack)
{
string txt = string.Empty;
txt = Request.Params["TextBox1"];
lblOutput.Text = "You entered : " + txt;
}
}
protected void Button1_Click(object sender, EventArgs e)
{ /* this does not */
string txt = string.Empty;
txt = Request.Params["TextBox1"];
lblOutput.Text = "You entered : " + txt;
}
Now if you include another simple HTML textbox (Not ASP) like this
<input type="text" id="mytextbox" name="mytextbox" /> // still it below the existing one
txt = Request.Params["mytextbox"]; // change to this line instead of TextBox1
Then it works in both places.
protected void Button1_Click(object sender, EventArgs e)
{ /* Now this works which is weird but it does */
If(IsPostback)
{
string txt = string.Empty;
txt = Request.Params["TextBox1"];
lblOutput.Text = "You entered : " + txt;
}
}
I therefore should close the question.
If you are forced to use the Request object instead normal asp:* controls, use it like this:
txt = Request["TextBox1"];
It will check all the HttpRequest collections.
The QueryString, Form, Cookies, or ServerVariables collection member
specified in the key parameter. If the specified key is not found,
then null is returned.
That is really fundamental stuff you're doing in that example, so I highly doubt it's a bug. From the example, it looks like you're going against the grain:
Markup
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" />
<asp:TextBox ID="TextBox2" runat="server" />
<asp:TextBox ID="TextBox3" runat="server" />
<asp:TextBox ID="TextBox4" runat="server" />
...
</asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /><br />
<asp:Label ID="lblOutput" runat="server" Text="Label"></asp:Label>
Code-behind
protected void Button1_Click(object sender, EventArgs e)
{
foreach (TextBox txtCtrl in PlaceHolder1.Controls.OfType<TextBox>())
{
//append the textbox value to the label
lblOutput.Text += String.Format("{0}<br/>", txtCtrl.Text);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
List<TextBox> txtList = PlaceHolder1.Controls.OfType<TextBox>().ToList();
for (int ctrlIndex = 0; ctrlIndex < txtList.Count; ctrlIndex++)
{
TextBox txtCtrl = txtList.ElementAt(ctrlIndex);
if (txtCtrl != null)
{
lblOutput.Text += String.Format("{0}<br/>", txtCtrl.Text);
}
}
}

Resources