dropdownList doesn't displays selected value - asp.net

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

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

C#/ASP.Net - Extract bit value of column in a gridview

I have a gridview that is SQL bound. In some of the columns there are bit values. When I use C# to get the values into the gridview, checkboxes are displayed. I need to extract the value of that column into text.
SqlConnection sConnection = new SqlConnection(MyConnectionString);
SqlCommand sCommand = new SqlCommand();
using (sConnection)
{
sCommand.Connection = sConnection;
sCommand.CommandText = "MyStoredProcedure";
sCommand.CommandType = CommandType.StoredProcedure;
sCommand.Connection.Open();
SqlDataReader reader = sCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
gridView.DataSource = reader;
gridView.DataBind();
}
for (int i = 0; i < gridView.Rows.Count; i++)
{
ListBox1.Items.Add(gridView.Rows[i].Cells[3].Text);
}
}
}
The gridview column data type is 'bit'. I do not have access to the database or stored procedure to change anything there. I need to somehow extract the '0' or '1' value, but when I do it like above, the text is blank.
I also tried to use 'GetOrdinal'. It returned a True/False value from the database, but I could not figure out how to get the value for each item in the gridview.
if (!reader.IsDBNull(reader.GetOrdinal("MyColumn1")))
{
ListBox1.Items.Add(reader.GetOrdinal("MyColumn1").ToString());
}
General overview:
You need to be able to find the CheckBox that's generated and get the value of it's "Checked" property.
To do this, you need to be able to use the FindControl() method on the GridViewRow.
To use FindControl, the CheckBox needs a predictable name.
To get a predictable name, you need to have that column be a TemplateColumn so that you can specify the name of the CheckBox in the markup on the ASPX page.
There's a full working set of code here: http://www.codeproject.com/Articles/25056/The-RIGHT-Way-to-Use-Checkboxes-in-a-NET-Repeater
This shows the code for a Repeater, but it's the same principle and general code for any DataBound control.
The code below should work with modifications to match your DB names:
<asp:TemplateField>
<ItemTemplate >
<asp:checkbox id="MyColumnNameCheckbox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
string defaultvalue = "0"; // To be used to display the value of the original bit field.
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkBx = (CheckBox)row.FindControl("MyColumnNameCheckbox");
if (chkBx != null && chkBx.Checked)
{
defaultvalue = "1";
}
}
I was able to figure it out. Thanks, David Stratton, for pointing me in the right direction.
I did it by assigning an id to the dynamically created control first. then did the FindControl()...
Control ctrl = GridView1.SelectedRow.Cells[4].Control[0];
ctrl.ID = "ctrl";
Boolean result = Convert.ToBoolean(((Checkbox)GridView1.Rows[0].Cells[4].FindControl("ctrl")).Checked);
TextBox1.Text = result.ToString();
This returns a value of "True" or "False"...
Thanks again.
Another way to resolve it:
bool result = (GridView1.SelectedRow.Cells[4].Control[0] as Checkbox).Checked;
TextBox1.Text = result.ToString();
it resolve the problem with less code :)

Blank Spaces also Bind When Binding a Dropdown list

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

How to databind a repeater from stored procedure?

I'm trying to databind my repeater but so far not having any luck. Anyone think that can show me where I'm going wrong? I have two functions at the moment by following some tutorials/examples but I was hoping to have just one... maybe not possible. Thanks!
HTML:
<ItemTemplate>
<tr class="row">
<td><asp:Label ID="TitleLabel" runat="server" Text=""></asp:Label></td>
<td><asp:Label ID="NameLabel" runat="server" Text=""></asp:Label></td>
<td><asp:Label ID="PhoneLabel" runat="server" Text=""></asp:Label></td>
<td><asp:Label ID="EmailLabel" runat="server" Text=""></asp:Label></td>
</tr>
</ItemTemplate>
VB
Protected Sub BindData()
Dim oCommand As SqlCommand
Dim oReader As SqlDataReader
Try
oCommand = DataAccess.GetSQLCommand("People_Retrieve", CommandType.StoredProcedure, SourceServer.ConnectionLocal)
oCommand.Connection.ChangeDatabase("MyDatabase")
oCommand.CommandTimeout() = 9000
oReader = oCommand.ExecuteReader()
PeopleRepeater.DataSource = oReader
PeopleRepeater.DataBind()
Catch ex As Exception
ErrorHandler.HandleError(ex)
Finally
oReader.Close()
oReader = Nothing
End Try
End Sub
Protected Sub PeopleRepeater_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles PeopleRepeater.ItemDataBound
Dim NameLabel As Label = CType(e.Item.FindControl("LabelName"), Label)
NameLabel.Text = e.Item.DataItem("Name")
Dim TitleLabel As Label = CType(e.Item.FindControl("TitleName"), Label)
NameLabel.Text = e.Item.DataItem("Title")
Dim PhoneLabel As Label = CType(e.Item.FindControl("PhoneName"), Label)
NameLabel.Text = e.Item.DataItem("Phone")
Dim EmailLabel As Label = CType(e.Item.FindControl("EmailName"), Label)
NameLabel.Text = e.Item.DataItem("Email")
End Sub
Use a SqlDataAdapter:
Using adap As New SqlDataAdapter(oCommand)
Dim table As New DataTable()
adap.Fill(table)
PeopleRepeater.DataSource = table
PeopleRepeater.DataBind()
End Using
I don't see where you're opening the connection either, so you might need to add that:
oCommand.Connection.Open()
Follow the steps
Create the stored procedure named as 'SelectPersonalDetails'
CREATE PROCEDURE SelectPersonalDetails
-- Add the parameters for the stored procedure here
#Email SYSNAME
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
BEGIN TRY
BEGIN TRANSACTION
BEGIN
SELECT Name,Title,Phone,Email FROM PersonalDetails
WHERE
Email = #Email
END
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
DECLARE #ERR AS VARCHAR(500)
SELECT #ERR = ERROR_MESSAGE()
RAISERROR(#ERR,16,1)
RETURN
END CATCH
END
Create dataset in order to bind the data in the repeater.
public DataSet Get_PersonaldetailbasedEmail()
{
try
{
DataSet oDS = new DataSet();
SqlParameter[] oParam = new SqlParameter[1];
oParam[0] = new SqlParameter("#Email", _sEmail);
oDS = SqlHelper.ExecuteDataset(DataConnectionString, CommandType.StoredProcedure, "SelectPersonalDetails", oParam);
return oDS;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return null;
}
}
Note: (i) SelectPersonalDetails is the stored procedure name
(ii) In order to select unique record from the table i have used emailid
(iii) I have assume the table name as PersonalDetails.
Create a user control page something like Personeldetails.ascx
/li>
/li>
/li>
/li>
Note above i have the html code for repeater but i don't know how to work around in this editor. anyways repeater id is same as your repeater and label ids are same as your label id.
Databind
Create a function to bind the data
public void FillArray(ArrayList alist)
{
ArrayList al = new ArrayList();
foreach (Object objRow in alist)
{
string sTitle = ((DataRow)objRow)["Title"].ToString();
string sName = ((DataRow)objRow)["Name"].ToString();
string sPhone = ((DataRow)objRow)["Phone"].ToString();
string sMail = ((DataRow)objRow)["Mail"].ToString();
al.Add(new string[]{ sTitle,sName,sPhone,sMail});
}
PeopleRepeater.DataSource = al;
PeopleRepeater.DataBind();
}
Now called Item databound
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string[] itemArray = ((string[])e.Item.DataItem);
Label myTitle = (Lable)e.Item.FindControl("TitleLabel");
Label myName = (Label)e.Item.FindControl("NameLabel");
Label myPhone = (Label)e.Item.FindControl("PhoneLabel");
Label myEmail = (Label)e.Item.FindControl("EmailLabel");
myTitle.Text = itemArray[0];
myName.Text = itemArray[1];
myPhone.Text = itemArray[2];
myEmail.Text = itemArray[3];
}
If you find the answer useful, please mark it as your answer else let me know....

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