Blank Spaces also Bind When Binding a Dropdown list - asp.net

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]");

Related

Delete row in GridView using Two DataKeys in condition

I want to delete a row in GridView and database as well.. I already have a stored procedure for the delete, the method is also created, but my problem is how can i use Two datakeys for my where clause. I've search and saw a lot of answers but they are using CommandArgument and that is applicable only in 1 datakeys.
I want something like this.
DELETE FROM TableName WHERE ID = Variable1 AND Name = Variable2
What i want is how can i retrieve the values of 2 datakeys in GridView if i set DataKeys like: DataKeys="ID, Name"
Any help would be appreciated.
Thanks
(if I correctly understood you)
stored procedure
Create Procedure [dbo].[Procedure_Name](
#Variable1 type(),
#Variable2 type() --you can add as many variables as you want, but then you have to add them in c# code as a parameters.
) as
delete from Table_Name
where Table_Name.Variable1 = #Variable1 AND Table_Name.Variable2 = #Variable2
with button in aspx code
<asp:Button ID="btnDeleteSomething" runat="server" Text="Delete Something" OnClick="btnDeleteSomething_Click"/>
then in c# codebehind
protected void btnDeleteSomething_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_NAME"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("Procedure_Name", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection.Open();
cmd.Parameters.Add("#Variable1", SqlDbType.VarChar, 70(its example with varchar)).Value = Variable1.Text(every Textbox, or label, or dropdownlist)
cmd.Parameters.Add("#Variable2", SqlDbType.Int).Value = Session["UserID]" - For example if u want do delete with parameter focused on user;
try
{
int rows = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
}
And it works fine without Datakeys at all. If u want to do it "with" then u have to add ControlParameter in your SqlDataSource. Hope it's going to help you.
Finally i found the solution on this link:
http://www.aspsnippets.com/Articles/Using-Multiple-DataKeyNames-DataKeys-in-ASPNet-GridView-with-examples.aspx
here is what exactly im looking for..
Dim rowIndex As Integer = TryCast(TryCast(sender, ImageButton).NamingContainer GridViewRow).RowIndex
Dim ID As Integer = Convert.ToInt32(GridView1.DataKeys(rowIndex).Values(0))`
Dim Name As String = GridView1.DataKeys(rowIndex).Values(1).ToString()`
Thanks

dropdownList doesn't displays selected value

I am new at asp.net. I have a dropdownList which displays all categories for a specific article. The problem is that when I want to edit an article it doesn't displays the value that exists as default selected in dropdownList.
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.EditItem)
{
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();
drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(Qry).Value;
//drpdKategoria.Items.FindByValue(string val).Selected = true;
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
EditArtikull.aspx
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<fieldset>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
</fieldset>
<br/>
ERROR:SystemNullReference Exception {"Object reference not set to an instance of an object."}
This line probably isn't going to find anything:
drpdKategoria.Items.FindByText(Qry)
Since Qry is a SQL statement:
string Qry = "select * from kategoria";
And I'm assuming that the display values in your DropDownList aren't SQL queries. Thus, when you call .Value on that first line, you're trying to de-reference something that isn't found (which is null), hence the error.
What item are you actually trying to find? If you want to select a default item, you need to be able to identify that item in some way. In your data that would be either by a known id value or a known emertimi value. For example, if you have a known emertimi value, it would be:
drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText("some known value").Value
To make this a little more robust, you probably want to add some null checking. Something like this:
var defaultValue = drpdKategoria.Items.FindByText("some known value");
if (defaultValue != null)
drpdKategoria.SelectedValue = defaultValue.Value

Insert unicode string to SQL Server using ASP.NET

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.

how to set column as readonly in gridview

I am using a gridview Edit to edit the values i have in my gridview, when i press edit, all columns can be edited, i would like that one of the columns is not allowed to be edited.
Is there any way i can do this?
This is my aspx code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="True"
onrowdeleting="GridView1_RowDeleting" AutoGenerateEditButton="True"
onrowediting="GridView1_RowEditing"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowupdating="GridView1_RowUpdating" >
</asp:GridView>
This is my aspx.cs code:
public void loadCustomer()
{
SqlConnection objConnection = new SqlConnection("Data Source=localhost;Initial Catalog=SampleApplication;Integrated Security=True");
objConnection.Open();
SqlCommand objCommand = new SqlCommand();
objCommand.CommandText = "Select * from Customer";
objCommand.Connection = objConnection;
objCommand.ExecuteNonQuery();
DataSet objds = new DataSet();
SqlDataAdapter objadap = new SqlDataAdapter(objCommand);
objadap.Fill(objds);
GridView1.DataSource = objds.Tables[0];
GridView1.DataBind();
objConnection.Close();
}
RowDataBound event of gridView1
((BoundField)gridView1.Columns[columnIndex]).ReadOnly = true;
I know this is really old but I need to put the answer here for others who shared my issue. Regardless, I've been struggling with this non-stop for a couple of days now. Everyone seems to be posting code for VB, when your problem is clearly posted in C#.
What you're looking for is:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[columntobedisabled].Enabled = false;
}
where 'columntobedisabled' is index number of the column to be disabled...eg. 1
In case of C# Website or WebForm enter the following code in Page_Load() in code behind file
protected void Page_Load(object sender, EventArgs e)
{
// Your code
((BoundField)GridView1.Columns[columnIndex]).ReadOnly = true;
}
Doing this will also help in overcoming the error
System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. Parameter name: index'
You need to give rights "ReadOnly= true" to that column which you not like to be edit.
e.g .
GridView1.columns[1].ReadOnly= true;
You can use this line in RowDataBound event of GridView.

Getting Row's Name in a DataList

I have a datalist and would like to pull the row names from the table that I am getting my values from for the datalist. Heres an example of what I would like to do.
<HeaderTemplate>
'Get data row names
'Maybe something like Container.DataItem(row)?
</HeaderTemplate>
If you are using a DataTable as a Data Source for your Data List you could use the OnItemCreated method and provide a custom handler for the ItemCreated event to add the column header values. I'm not sure why you would want to do this. It sounds like a Repeater or GridView might be better suited to your needs. At any rate, here's the code.
<asp:DataList ID="DataList1" runat="server" OnItemCreated="DataList1_ItemCreated"
ShowHeader="true" >
<HeaderTemplate>
</HeaderTemplate>
</asp:DataList>
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT [id], [name], [email], [street], [city] FROM [employee_tbl]", conn);
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dt);
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
protected void DataList1_ItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
foreach (DataColumn col in dt.Columns)
{
Literal lit = new Literal();
lit.Text = col.ColumnName;
e.Item.Controls.Add(lit);
}
}
}
You could do the following, but I doubt it would work. I don't believe DataItems are available at the point when the Header is being created.
((DataRowView)Container.DataItem).DataView.Table.Columns
If this works, you can loop through this collection and inspect each item's ColumnName property.
A better idea would be to either:
Create a property in codebehind that returns a List<string> of appropriate column headers. You can refer to this property in markup when you're declaring the header.
Add a handler for the ItemDataBound event and trap header creation. You will still need a way to refer to the data elements, which probably haven't been prepped at this point.

Resources