I have created a stored procedure as follows:
CREATE PROCEDURE spIns_nav_Content
#CategoryID nVarChar(50),
#ContentText nVarChar(Max)
AS
INSERT INTO dbo.nav_Content(CategoryID, ContentText, Active)
VALUES (#CategoryID, #ContentText, 1)
In my ASP.net application I have a textbox and a button. My aspx page looks like this:
<div>
<asp:Label ID="Label1" runat="server" Text="Text here"></asp:Label>
<asp:TextBox ID="txtContent" runat="server" Font-Names="ML-TTKarthika"></asp:TextBox>
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
<asp:Label ID="lblContent" runat="server" Font-Names="ML-TTKarthika"></asp:Label>
</div>
When clicked on btnUpload I need to save the non-English (Malayalam) text in txtContent to database as unicode characters. The click event is as follows:
protected void btnUpload_Click(object sender, EventArgs e) {
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TestMalayalamConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand sqlCmd = con.CreateCommand();
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "spIns_nav_Content";
sqlCmd.Parameters.Add("#CategoryID", SqlDbType.NVarChar, 50).Value = "Rashriyam";
sqlCmd.Parameters.Add("#ContentText", SqlDbType.NVarChar, -1).Value = txtContent.Text;
sqlCmd.ExecuteScalar();
con.Close();
lblContent.Text = txtContent.Text;
}
When I see my db table the value in ContentText is in English. How can I change this?
What's the purpose of the font?
If it's mapping english characters to a foreign character set for display purposes (which as far as I can tell it does), then the DB is going to store english characters, as they are what is being typed in.
I typed hello into a font preview and could see that there were two characters the same for the letter l, then the o.
Effectively, all you are doing is substituting the typed english characters for the foreign character set at display time only. The underlying characters are still english.
To store Unicode characters, you'd have to actual enter unicode characters into the input control.
Related
I am currently busy creating a simple website. Files get copied on to my FTP server. On my web page is a Textbox,button and gridview.
Everything is working fine, when i load my website the gridview is not visible until you have search for something.At the moment i have no search code for my search button, i coded it to load every file into the grid view.
I now want to add some filtering when you click the search button, but i have no clue on how to do it and the Internet only shows how to do it with a database, but i am using New List object.
See my example code below. (This currently add all the files to the gridview)
Dim filePaths() As String = Directory.GetFiles(Server.MapPath("~/Uploads/IIC/"))
Dim dt As New DataTable
dt.Columns.Add("FileName", GetType(String))
dt.Columns.Add("FilePath", GetType(String))
dt.Rows.Clear()
For Each filePath As String In filePaths
dt.Rows.Add(Path.GetFileName(filePath), filePath)
Next
If GridView2.Columns.Count > 2 Then
For x = 2 To GridView2.Columns.Count - 1
GridView2.Columns.RemoveAt(2)
Next
End If
Dim FileNameCol As New BoundField
Dim FilePathCol As New BoundField
FileNameCol.DataField = "FileName"
FileNameCol.HeaderText = "FileName"
FilePathCol.DataField = "FilePath"
FilePathCol.DataField = "FilePath"
GridView2.Columns.Add(FileNameCol)
GridView2.Columns.Add(FilePathCol)
GridView2.DataSource = dt.Select("FileName LIKE '%" & TextBox1.Text & "%'")
GridView2.DataBind()
Any help showing me how to filter the gridview will help me a lot as i haven't really worked with lists before.
Note: The gridview does not use a Database
Designer Code for Gridview2
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" PageSize="10" AllowPaging="true"
EmptyDataText = "No files uploaded" Width="251px">
<Columns>
<asp:BoundField DataField="Text" HeaderText="FileName" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
You can achieve that using a DataTable.
It has a .Select() function in which you can filter specific records inside the datatable (Like the WHERE part in a query but instead from a database, you are using it in a datatable)
Try this:
Dim filePaths() As String = Directory.GetFiles(Server.MapPath("~/Uploads/IIC/"))
Dim dt As New DataTable
dt.Columns.Add("FileName", GetType(String))
dt.Columns.Add("FilePath", GetType(String))
dt.Rows.Clear()
For Each filePath As String In filePaths
dt.Rows.Add(Path.GetFileName(filePath), filePath)
Next
If GridView2.Columns.Count > 1 Then
For x = 1 To GridView2.Columns.Count - 1
grdApproval.Columns.RemoveAt(1)
Next
End If
Dim FileNameCol As New BoundField
Dim FilePathCol As New BoundField
FileNameCol.DataField = "FileName"
FileNameCol.HeaderText = "FileName"
FilePathCol.DataField = "FilePath"
FilePathCol.HeaderText = "FilePath"
GridView2.Columns.Add(FileNameCol)
GridView2.Columns.Add(FilePathCol)
GridView2.DataSource = dt.Select("FileName LIKE '%" & txtYourSearchBox.Text & "%'")
GridView2.DataBind()
when i Bind the dropdownlistHostelRoomType, it binds with empty spaces left above.. i dont have any idea why this is happening. help me getting out from this issue please.. My Code:
<div>
<fieldset>
<legend>Hostel Details </legend>
<asp:Label ID="LabelHostelRoomType" runat="server" Text="Room Type"></asp:Label>
<asp:DropDownList ID="DropDownListHostelRoom" runat="server" DataTextField="HTypeName"
DataValueField="_HRTypID" OnSelectedIndexChanged="DropDownListHostelRoom_SelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="GridViewHostelRoom" runat="server">
</asp:GridView>
</fieldset>
</div>
private void FillHostelRoomType()
{
SqlConnection cn = new SqlConnection(#"Data Source=.;Initial Catalog=_uniManagement;Integrated Security=True");
string sqlDropdownHostelRoom = String.Format("SELECT [_HRTypID], [HTYPeNAME] FROM [_HOSTELS_Room_TYPE]");
SqlCommand cmd = new SqlCommand(sqlDropdownHostelRoom);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DropDownListHostelRoom.DataSource = dt;
DropDownListHostelRoom.DataBind();
}
protected override void OnInit(EventArgs e)
{
DropDownListHostelRoom.AppendDataBoundItems = true;
DropDownListMemberType.AppendDataBoundItems = true;
FillHostelRoomType();
FillHostelMember();
base.OnInit(e);
}
Most likely, there are empty spaces in the source database. In your SQL statement, you should be able to use RTRIM() around the field names to eliminate the issue.
Another possible cause might be that the field in the DB is CHAR with a specified length. If that is the case, even if there are no spaces, retrieving it will always give you exactly that many spaces, so SQL Server will pad the end with enough blank spaces to fit.
For example, a field defined as CHAR(10) with the data "DAVID" in it will be returned as "DAVID " (David appended with five blank spaces to bring the total up to 10)
Either way, RTRIM should fix it.
string sqlDropdownHostelRoom = String.Format("SELECT [_HRTypID], RTRIM([HTYPeNAME]) AS HTYPeNAME FROM [_HOSTELS_Room_TYPE]");
I wrote the code to query the database, but now do not know how to get the text into my two labels 'txtTitle' & 'txtBody'
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["blcDocumentationConnectionString"].ConnectionString);
// Create Command Object
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
pnlNew.Visible = false;
pnlView.Visible = true;
try
{
// Open Connection
thisConnection.Open();
// Create SELECT statement with named parms
nonqueryCommand.CommandText = "SELECT DocumentTitle,DocumentBody FROM tblDocument WHERE DocumentID = #DocumentID";
// Add parms to Command parms collection
nonqueryCommand.Parameters.AddWithValue("#DocumentID", GridView1.SelectedValue);
// Execute query statement
nonqueryCommand.ExecuteNonQuery();
// Populate Labels
GridViewRow row = GridView1.SelectedRow;
lblTitle.Text = row.Cells[1].Text;
lblBody.Text = row.Cells[2].Text;
}
finally
{
// Close Connection
thisConnection.Close();
}
}
<asp:Panel ID="pnlView" runat="server" Visible="False" CssClass="pnlView">
<h1 style="background-color: #CCE6FF">
<asp:Label ID="lblTitle" runat="server" Text="Label"></asp:Label></h1>
<p>
<asp:Label ID="lblBody" runat="server" Text="Label"></asp:Label></p>
<p style="background-color: #EFEFEF">
<asp:Button ID="btnEdit" runat="server" Text="Edit This Document" OnClick="btnEdit_Click" /> or
cancel</p>
</asp:Panel>
Your code shows that you have a table filled with documents IDs (I'm assuming you already bound this correctly in some other part of your code)
You used the SelectedIndexChanged event correctly, but why are you executing another query inside? If executing the query is intentional, why are you binding your labels to old data? row.cells[].value holds old information, not the information you re-queried. If you want the information you re-queried for, get that info directly from the result set. Also, that result set will return nothing unless you change nonqueryCommand.ExecuteNonQuery(); to nonqueryCommand.ExecuteDataSet();
Reiterating what User:rkw mentioned above. ExecuteNonQuery will not get any data back from the database. You need to use either DataReader ( http://msdn.microsoft.com/en-us/library/haa3afyz.aspx ) or use the ExecuteDataset and put the information into a DataSet and then read from it. When you say ExecuteNonQuery you are basically telling the SQL server to execute commands but not expecting any data back from the SQL Server.
I have a listview with some data bound to it.
In this data are column for an address.
How would I go about accessing these data items in code behind so I can concatenate them into one easy variable and miss out columns that have no data in, i have fields:
address
address1
town
county
postcode
I don't have a problem with the concatenation just accessing the data items.
Thanks J.
UPDATED
I am getting data out via a dataset and binding it to a listview.
Is it possible to access data items in the code behind to format or do whatever i want with them then showing it in the list view such as, concatenating the address fields into one variable?
so instead of writing:
DataBinder.Eval(Container.DataItem, "address") & ", " & DataBinder.Eval(Container.DataItem, "address1") & ", " & DataBinder.Eval(Container.DataItem, "town") etc...
in the actual list view i could do this in the code behind in a string variable then show the variable in the list view?
'select command
Dim cmdSchedule As SqlCommand = New SqlCommand()
cmdSchedule.Connection = keypadSQL
cmdSchedule.CommandText = "spSchedule"
cmdSchedule.CommandType = CommandType.StoredProcedure
'data adapter
Dim daSchedule As SqlDataAdapter = New SqlDataAdapter
daSchedule.SelectCommand = cmdSchedule
'data set
Dim dsSchedule As DataSet = New DataSet()
daSchedule.Fill(dsSchedule, "Schedule")
lvSchedule.DataSource = dsSchedule
lvSchedule.DataBind()
cmdSchedule.Dispose()
First put your items into accessible controls in the ListView, such as a label or literal.
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<asp:Label ID="lblAddress" runat="server" Text="<%= Eval("address") %>" />
</ItemTemplate>
</asp:ListView>
Then you can loop through the items and using FindControl, pull each string out individually.
Dim items As List(Of ListViewDataItem) = ListView1.Items
For Each item As ListViewDataItem In items
Dim strAddress As String = CType(item.FindControl("lblAddress"), Label).Text
Next
UPDATED
I'd think the best way would be to format it in SQL Stored Procedure and return it as a new field. Something like this:
SELECT *, address + ', ' + address1 + ', ' + town ', ' + county + ', ' postcode AS fullAddress
FROM ...
Then you'd just have to use <%= DataBinder.Eval(Container.DataItem, "fullAddress") %> to get the formatted address. You could even format it with HTML in the SP as long as you're weary of potential injection attacks (not sure of the original address input method).
I trying to save employee image in employee database. I have three field in database table empid, empname, empimage. Here is my database part.
CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)
In the button click event, i have written the following code:
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
connection = new SqlConnection(conn);
connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(#enm, #eimg)SELECT ##IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("#enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("#eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
connection.Close();
}
And Here is my form:
<asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
<asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
<asp:FileUpload ID="imgUpload" runat="server" />
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
 
<asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
<br />
<hr />
<asp:Image ID="Image1" style="width:200px" Runat="server" />
But when I am uploading any image and clicking on submit button getting this error "Object reference not set to an instance of an object." Pls somebody point out my error.
Thanks,
Sumit
Object Reference errors only occur when an object is not initialized and you try to reference it. This could be any object you are referencing within your code. If you step through the code while debugging, you can see exactly which reference is null.
You have an if statement that initializes the imgByte object:
imgByte = new Byte[File.ContentLength];
If the img object turns out to be null, that code does not run. Then you reference the imgByte here, regardless of whether or not the img was null:
cmd.Parameters.AddWithValue("#eimg", imgByte);
Check the the HttpPostedFile object itself is not null and move your imgByte object initialization outside the if statement. Also, the name File is already used by the System.IO.File object. You may want to rename it just to be safe.
I would rearrange your ADO.NET code a bit - make it safe and more reliable; also, I would make sure to separate the two SQL statements in your "sql" string by a semicolon to make it clear to SQL that this is two commands, really:
string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
using(connection = new SqlConnection(conn))
{
string sqlStmt = "INSERT INTO dbo.EmpDetails(empname, empimg) " +
"VALUES(#enm, #eimg); SELECT ##IDENTITY";
using(SqlCommand cmd = new SqlCommand(sqlStmt, connection))
{
cmd.Parameters.AddWithValue("#enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("#eimg", imgByte);
connection.Open();
int id = Convert.ToInt32(cmd.ExecuteScalar());
connection.Close();
lblResult.Text = String.Format("Employee ID is {0}", id);
}
}
Any luck with this?? Otherwise you should really step through the code in the debugger and see where in your code you reference something that is NULL (and you don't check for that condition).
Marc
While i am debugging this code i am
getting exception in this
line..."string conn =
ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;"
Exception is: Object reference not set
to an instance of an object.
You need to add a connection string named EmployeeConnString to web.config.
Your exception handler does not distinguish where exactly an exception occurred, and issues a single error message for any possible error.