I have multiple textboxes that goes into a table called dbo.skills
dbo.Skills SkillID (PK- AutoIncrement) | SkillName
So when I used this method, the name is not getting stored but only SkillID is getting auto-incremented. Here is my .cs code
public void InsertSkillInfo()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
try
{
for (int i = 1; i <= 4; i++)
{
conn.Open();
//string skill = (TextBox)((Page.FindControl("TextBox" + i.ToString()))).Text;
var skill = "";
var control = Page.FindControl("TextBox" + i.ToString()) as TextBox;
if (control != null)
{
skill = control.Text;
}
const string sqlStatement = "INSERT INTO Skills (SkillName) VALUES (#SkillName)";
SqlCommand cmd = new SqlCommand(sqlStatement, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#SkillName", skill);
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
After entering values in textboxes, table looks like this-
Dbo.Skills
SkillID | SkillName
1 |
2 |
3 |
4 |
ASPX code:
<asp:Label ID="Label1" class="caption" runat="server" Text="Skill Name"></asp:Label>
<asp:TextBox ID="TextBox1" class="box" runat="server"></asp:TextBox> <br /> <br />
<asp:Label ID="Label2" class="caption" runat="server" Text="Skill Name"></asp:Label>
<asp:TextBox ID="TextBox2" class="box" runat="server"></asp:TextBox> <br /> <br />
<asp:Label ID="Label3" class="caption" runat="server" Text="Skill Name"></asp:Label>
<asp:TextBox ID="TextBox3" class="box" runat="server"></asp:TextBox> <br /> <br />
<asp:Button ID="Button1" class="box" runat="server" Text="Insert"
onclick="Button1_Click" /> <br /><br /><br />
Related
I am using AutoCompleteExtender in asp.net to fetch name and designation based on token(empno).
The is pulled from database and I could see it in the network tab of Chrome Dev-tools. But it is not rendered as suggestion list.
My attempt for the code:
<div class="modal-body">
<div class="form-group">
<label for="pToken">Token</label>
<asp:TextBox ID="pToken" runat="server" CssClass="form-control" placeholder="Enter Token No" />
<ajaxcontrol:AutoCompleteExtender runat="server"
ID="acToken" TargetControlID="pToken" MinimumPrefixLength="3"
EnableCaching="true" FirstRowSelected="false"
ServiceMethod="getPatients" ServicePath="CheckPatientDetails.aspx"
CompletionSetCount="6" DelimiterCharacters="|"
CompletionListItemCssClass="AutoCompleteExtender_CompletionListItem"
CompletionListHighlightedItemCssClass="AutoCompleteExtender_HighlightedItem"
CompletionListCssClass="AutoCompleteExtender_CompletionList">
</ajaxcontrol:AutoCompleteExtender>
</div>
<div class="form-group">
<label for="pName">Name</label>
<asp:TextBox ID="pName" runat="server" CssClass="form-control" placeholder="Enter patient name" required />
</div>
<div class="form-group">
<label for="pDesig">Designation</label>
<asp:TextBox ID="pDesig" runat="server" CssClass="form-control" placeholder="Enter designation" />
</div>
<div class="form-group">
<label for="pType">Type</label>
<asp:DropDownList ID="pType" runat="server" CssClass="form-control" required>
<asp:ListItem Value="E" Selected="True">Employee</asp:ListItem>
<asp:ListItem Value="I">In Patient</asp:ListItem>
<asp:ListItem Value="O">Out Patient</asp:ListItem>
<asp:ListItem Value="X">Others</asp:ListItem>
</asp:DropDownList>
</div>
The backend code for the same is below :
[WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public static List<Patient> getPatients(string prefixText, int count)
{
List<Patient> patientList = new List<Patient>();
OracleConnection con = null;
OracleDataReader odr = null;
string query = "select nvl(emp.empid,'') token,DECODE(SHORTNAME,NULL,FIRSTNAME,SHORTNAME) name,DESIGSHORT desigdesc" +
" from employee emp join designation desig on (emp.desigcode = desig.desigcode and desig.isactive = 'Y') " +
" where empid like '%" + prefixText + "%' and emp.EMPSTATUS = 'A' order by empid";
try
{
con = getHRMSConnection();
con.Open();
using (con)
{
using (OracleCommand cmd = new OracleCommand(query, con))
{
odr = cmd.ExecuteReader();
Patient patient = null;
while (odr.Read())
{
patient = new Patient();
patient.setToken(Convert.ToString(odr["token"]));
patient.setName(Convert.ToString(odr["name"]));
patient.setDesignation(Convert.ToString(odr["desigdesc"]));
patientList.Add(patient);
}
}
}
}
catch (Exception ex)
{
}
return patientList;
}
There are many reasons for the issue you are facing. Starting with basic check if service path is correct or not.
Secondly, have you declared with [webmethod] above your function fetching data.
The task is done now, I am getting the autocomplete rendered properly. Posting for those who may refer to this later on.
I used this link to get the autocomplete rendered on modal.
Autocomplete extender not working inside modal popup extender
Now my modal body is
<div class="modal-body">
<div class="form-group">
<asp:AutoCompleteExtender ServiceMethod="GetSearch" MinimumPrefixLength="2" CompletionInterval="10"
EnableCaching="false" CompletionSetCount="10" TargetControlID="pToken" ID="AutoCompleteExtender2"
runat="server" FirstRowSelected="false" CompletionListCssClass="autocomplete_completionListElement" CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem">
</asp:AutoCompleteExtender>
<label for="pToken">Token</label>
<asp:TextBox ID="pToken" runat="server" CssClass="form-control" placeholder="Enter Token No"/>
</div>
<div class="form-group">
<label for="pName">Name</label>
<asp:TextBox ID="pName" runat="server" CssClass="form-control" placeholder="Enter patient name" required />
</div>
<div class="form-group">
<label for="pDesig">Designation</label>
<asp:TextBox ID="pDesig" runat="server" CssClass="form-control" placeholder="Enter designation" />
</div>
<div class="form-group">
<label for="pType">Type</label>
<asp:DropDownList ID="pType" runat="server" CssClass="form-control" required>
<asp:ListItem Value="E" Selected="True">Employee</asp:ListItem>
<asp:ListItem Value="I">In Patient</asp:ListItem>
<asp:ListItem Value="O">Out Patient</asp:ListItem>
<asp:ListItem Value="X">Others</asp:ListItem>
</asp:DropDownList>
</div>
</div>
And server side code is :
[WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> GetSearch(string prefixText, int count)
{
OracleConnection con = null;
OracleDataAdapter oda = null;
DataTable dt;
prefixText = prefixText.ToLower();
DataTable Result = new DataTable();
List<string> Output = new List<string>();
string str = "select nvl(emp.empid,'') ||'('||DECODE(SHORTNAME,NULL,FIRSTNAME,SHORTNAME)||','|| DESIGSHORT ||')' employee" +
" from employee emp join designation desig on (emp.desigcode = desig.desigcode and desig.isactive = 'Y') " +
" where lower(empid) like '%" + prefixText + "%' and emp.EMPSTATUS = 'A' order by empid";
con = getHRMSConnection();
using (con)
{
try
{
con.Open();
oda = new OracleDataAdapter(str, con);
dt = new DataTable();
oda.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
Output.Add(dt.Rows[i][0].ToString());
}
}
catch (Exception ex)
{
}
}
return Output;
}
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 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.
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
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Rendering bytes from sql server to an image control?
<asp:ListView ID="lvGallery" runat="server" DataSourceID="SqlDataSource1">
<LayoutTemplate>
<table runat="server" id="tableGallery">
<tr runat="server" id="itemPlaceHolder">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr><td>
<div class="box_img2">
<div class="g_size">
<a runat="server" id="linkImage"><img id="Image1" runat="server" src="MyImage.jpg" /></a>
</div>
</div>
</td></tr>
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=CHANDAN-PC;Initial Catalog=Metamorphism;User ID=sa;password=chandan;"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [Image] FROM [GalleryImages]"></asp:SqlDataSource>
public void ProcessRequest(HttpContext context)
{
//write your handler implementation here.
string username = Convert.ToString(context.Request.QueryString["username"]);
if (username != null)
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
byte[] arrContent;
DataRow dr;
string strSql;
strSql = "Select Image from GalleryImages where username = '" + username + "'";
da = new SqlDataAdapter(strSql, connection.ConnectionString);
da.Fill(ds);
dr = ds.Tables[0].Rows[0];
arrContent = (byte[])dr["ImageFile"];
context.Response.ContentType = "jpeg";
context.Response.OutputStream.Write(arrContent, 0, arrContent.Length);
context.Response.End();
}
}
I have added httphandlers tag in web.config.
I think you need to change this
<div class="box_img2">
<div class="g_size">
<a runat="server" id="linkImage">
<img id="Image1" runat="server" src='<%# Eval( HttpContext.Current.Request.QueryString["username"] ,"YourGenericHandler.ashx?username={0}") %>' /></a>
</div>
</div>