Getting Row's Name in a DataList - asp.net

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.

Related

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

Gridview selected value always returns 0?

I am trying to delete a row from a gridview if "Web drop course" option is selected. Here is the UI:
And the code:
for (int i = 0; i < showCourses.Rows.Count; i++)
{
if (((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue == "1")
{
dropList.Add(showCourses.Rows[i].Cells[2].Text +showCourses.Rows[i].Cells[3].Text );
}
}
Here is the dropdown list:
<asp:ListItem Selected="True" Value="0">No Action</asp:ListItem>
<asp:ListItem Value="1">Web Drop Course</asp:ListItem>
The problem is, ((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue always returns 0 whether I choose No action or Web drop course. Can anyone see the problem?
Thanks
You are most likely not protecting against rebinding your data on postback. When your event that causes postback fires, the page load event fires before this. If you are binding in page load without a check for postback, you are basically resetting your data and then going into your event handler.
The page life cycle might be a good read: Page Life Cycle
Considering your previous post, you are rebinding the gridview on each postback. Wrap those lines with a !IsPostback conditional. Better wrap those into a method (say PopulateGrid()) and call it. Then, you can re-call that method in other situations where you might need to rebind the data (OnPageIndexChanged for example). Change your Page_Load method like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
PopulateGrid();
}
}
private void PopulateGrid()
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string query = "select * from RegisterTable where StudentID='" + MyGlobals.currentID + "'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
showCourses.DataSource = tab;
showCourses.DataBind();
}
}

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.

datagridview in asp.net retrieve value

i am working on visual stdio 2008 and my database is in sql server 2005
MY table has three columns
1. SenderName
2. RecieverName
3. Message
i have displayed this table in GridView and add a button named as Reply
so my grid view look's some what like this
SenderName|RecieverName| MessAge|REPLY BUTTON
now this what i want to do
when Button is Clicked in My gridView i need to get data of that specific row
i.e Sender's NAme so that i can Reply him/her ?
can any one help????
Here's a sample:
Markup:
<asp:GridView
runat="server"
ID="gvEmails"
OnSelectedIndexChanged="gvEmails_SelectedIndexChanged">
<Columns>
<asp:ButtonField CommandName="Select" ButtonType="Button" Text="Send" />
</Columns>
</asp:GridView>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("SenderName");
dt.Columns.Add("ReceiverName");
dt.Columns.Add("Message");
DataRow dr;
dr = dt.NewRow();
dr["SenderName"] = "John Doe";
dr["ReceiverName"] = "Jane Doe";
dr["Message"] = "Hi, Jane.";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["SenderName"] = "Michelle Smith";
dr["ReceiverName"] = "Mike Smith";
dr["Message"] = "Yo, Mike.";
dt.Rows.Add(dr);
gvEmails.DataSource = dt;
gvEmails.DataBind();
}
protected void gvEmails_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = gvEmails.SelectedRow;
Response.Write("Send email to " + row.Cells[1].Text);
}
there is a selected index changed function in the properties.
Captuer the selected index and get the cell value of that selected index.
Then continue whtever u want.
There are many different ways of doing this. The easiest, if you only need a single value, would be to bind the value to the CommandArgument of your Reply button. Then add an OnClick handler to your button. Then in the OnClick method you can get the name from the CommandArgument.
If you need more than a single value from the row, you will need to do a little more work. You can setup an event handler on the GridView to capture the event of the index changing. This will provide some event arguments that has a NewSelectedIndex. That will tell you what row was selected. Depending on how your data is bound to your GridView, you can access the data again to get the values you need, or you can set the columns to be a DataKey in the GridView and access them that way.

How would I search through a DataSet and change data in it before it gets bound?

Try
Dim ds As DataSet = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings("connstr").ConnectionString, CommandType.StoredProcedure, "Get_All", New SqlParameter("#userid", Session("userid")))
rptBundles.DataSource = ds.Tables(0)
Catch ex As Exception
showerror(ex, Me)
End Try
That is the code, I want to be able to parse through it and find certain rows that have a certain boolean set to 1 and then edit other variables in that row accordingly, how would I do this, I tried making a For Each row nested in a For Each table but when I tested it the repeater never populates with data...
For Each ds_table As DataTable In ds.Tables
For Each ds_row As DataRow In ds_table.Rows
If ds_row("isScorm") = 1 Then
ds_row("totalLessons") = 100
ds_row("TotalQuestions") = 100
ds_row("lessonscompleted") = 50
ds_row("TotalCorrect") = 50
End If
Next
Next
Only when I remove that code does the repeater populate as expected, but I got no errors!
If you're using a Repeater, or whatever datasource bound control, I would use the ItemDataBound event and set those values to your controls.
If this was your basic HTML
<html>
<asp:Repeater id="repeater" runat="server" OnItemDataBound="repeater_ItemDatabound">
<ItemTemplate>
<span><%# DataBinder.Eval(Container.DataItem, "isScorm") %></span>
<span id="totalLessonsSpan" runat="server"><%# DataBinder.Eval(Container.DataItem, "totalLessons") %></span>
</ItemTemplate>
</asp:Repeater>
</html>
I would have this in the code behind
protected void repeater_ItemDatabound(object sender, RepeaterItemEventArgs e)
{
DataRow row = e.Item.DataItem as DataRow;
if (row == null) { }
else
{
int isScorm = 0;
int.TryParse(Convert.ToString(row["isScorm"]), out isScorm);
if (isScorm > 0)
{
HtmlGenericControl totalLessonsSpan = e.Item.FindControl("totalLessonsSpan") as HtmlGenericControl;
totalLessonsSpan.Text = "100";
}
}
}
You probably don't want to loop through the data and swap it there, then bind when you can do it during the bind.
Alternately, something I hate that DB's do because of my need for data integrity, is change it in your SQL select with case statements.
Does adding rptBundles.DataBind() after setting DataSource fix the problem?
Also, you might want to check out the DataTable.Select method to only select (and then modify) rows where isScorm = 1.

Resources