Get Gridview dropdownList value - asp.net

work on asp.net vs05.I have a grid
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False"
DataKeyNames="StudentID" OnSelectedIndexChanged="GridView3_SelectedIndexChanged"
OnRowDataBound="GridView3_RowDataBound">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="StudentID" ReadOnly="True"
SortExpression="StudentID" />
<asp:BoundField DataField="StudentName" HeaderText="StudentName" />
<asp:TemplateField HeaderText="DivisionName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("StudentName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
Width="160px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" CommandName="Select" HeaderText="Update"
Text="Update" />
</Columns>
</asp:GridView>
Using The button Click i want to save value on database.But i can not read value from the dropdownlist
protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectRow = GridView3.SelectedRow;
String ID = selectRow.Cells[0].Text;
String Name = selectRow.Cells[1].Text;
//String Dis = selectRow.Cells[2].Text;
String Dis =
((DropDownList)sender).FindControl("DropDownList1").ToString();
//**want to get this value**
}
How can i get ddl selected value?i want to put the object of a class on ddl .Bellow code work on desktop ,Want same thing on web.
DropDownList1.DisplayMember = "CommercialRegionName";
foreach (class oItem in _collection)
{
DropDownList1.Items.Add(oItem);
//**want to save object,Not any object item like:oItem.Name.**
}

protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectRow = GridView3.SelectedRow;
String ID = selectRow.Cells[0].Text;
String Name = selectRow.Cells[1].Text;
//String Dis = selectRow.Cells[2].Text;
//PROBABLY YOU WANT TO GET ITEM FROM SELECTED ROW'S DROPDOWN
var ddl = (selectRow).FindControl("DropDownList1") as DropdownList;
if(dis!=null){
var s=ddl.SelectedItem.Text;
}
}

Related

how to set tooltip on asp boundfield datafield hedertext inside of gridview in asp.net?

I have grid view.there are two BoundField.here i want to set tooltip on BoundField DataField HeaderText Topic.
code.
<asp:GridView ID="Dgvlist" runat="server" >
<Columns>
<asp:BoundField DataField="topic" HeaderText="Topic" />
<asp:BoundField DataField="question" HeaderText="Question" />
</Columns>
</asp:GridView>
there are any solution?
There are 3 usual ways to set tooltip on BoundField column:
1) Using code-behind RowDataBound event
protected void Dgvlist_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
e.Row.Cells[0].ToolTip = DataBinder.Eval(e.Row.DataItem, "Topic", string.Empty);
}
}
2) Using code-behind RowCreated event
protected void Dgvlist_RowCreated(object sender, GridViewRowEventArgs e)
{
foreach (TableRow row in Dgvlist.Controls[0].Controls)
{
row.Cells[0].ToolTip = DataBinder.Eval(e.Row.DataItem, "Topic", string.Empty);
}
}
3) Convert to TemplateField and use Label control
<asp:GridView ID="Dgvlist" runat="server" ...>
<Columns>
<asp:TemplateField HeaderText="Topic">
<asp:Label ID="TopicID" runat="server" Text='<%# Eval("topic") %>' ToolTip='<%# Eval("topic") %>'>
</asp:Label>
</asp:TemplateField>
<asp:BoundField DataField="question" HeaderText="Question" />
</Columns>
</asp:GridView>
The actual implementation depends on what method you're using.
Related issue:
How to add tooltip to BoundField
One hacky way to achieve this is to convert your BoundField to TemplateField option.
Convert this:
<asp:BoundField DataField="topic" HeaderText="Topic" />
To this:
<asp:TemplateField HeaderText="Topic">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Topic") %>' ToolTip ='<%# Bind("Topic") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Or From code behind you can do it in RowDataBound event like this
protected void Dgvlist_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
e.Row.Cells[i].ToolTip = e.Row.Cells[i].Text;
}
}

Updating gridview row is not saving the data

I am having issue when updating gridview! everything is seems to be working. but when i hit finish editing the data will not save!
but when i click edit the correct fields prompt me to enter new value but it wont save!
here is my asp
<asp:GridView ID="GridView1" runat="server" CssClass="report"
AutoGenerateColumns="False" onrowediting="GridView1_RowEditing"
DataKeyNames="TimeID" onrowupdating="GridView1_RowUpdating"
onrowcommand="GridView1_RowCommand"
onrowcancelingedit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="date" Visible="true" ReadOnly="true" HeaderText="Date" />
<asp:BoundField DataField="Description" HeaderText="Stage Description" ReadOnly="True" />
<asp:TemplateField HeaderText="Start Time">
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtStartTime" ValidationGroup="1" Width="90px" class="TimeEntry" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="txtStartTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Time">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEndTime" class="TimeEntry" ValidationGroup="1" Width="90px" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator66" ControlToValidate="txtEndTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TimeInHours" HeaderText="Time Time (Hours)" ReadOnly="True" />
<asp:CommandField ShowEditButton="true" ShowCancelButton="true"
ButtonType="Image" EditImageUrl="~/images/edit_record.jpg"
CancelImageUrl="~/images/edit_no.jpg"
UpdateImageUrl="~/images/update_record.jpg" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="lnbCopy" runat="server" AlternateText="Delete"
CommandName="DeleteRecord" CommandArgument='<%# Bind("TimeID") %>' OnClientClick="return confirm('Are you sure you want to delete this row?');" ImageUrl="~/images/delete_record.jpg" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblTimeID" runat="server" Text='<%# Eval("TimeID") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is what i have done in behind code
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {
GridView1.EditIndex = e.NewEditIndex;
loadTable();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {
GridView1.EditIndex = -1;
loadTable();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
var StartTime = row.FindControl("txtStartTime") as TextBox;
var EndTime = row.FindControl("txtEndTime") as TextBox;
var id = row.FindControl("lblTimeID") as Label;
SqlConnection conn = new SqlConnection(conStr.GetConnectionString("myServer1"));
SqlCommand comm = new SqlCommand();
comm.CommandText = "UPDATE CDSTimeSheet SET StartTime = #StartTime, EndTime = #EndTime ,timeElapsed = datediff(minute,#startTime , #EndTime), timeInSeconds = datediff(second,#startTime , #EndTime) WHERE TimeID = #id";
comm.Connection = conn;
comm.Parameters.AddWithValue("#id", id.Text);
comm.Parameters.AddWithValue("#StartTime", StartTime.Text);
comm.Parameters.AddWithValue("#EndTime", EndTime.Text);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
GridView1.EditIndex = -1;
loadTable();
}
what am i doing wrong?
It sounds a lot like you are not calling DataBind on your grid after updating the underlying data. After you perform the update (possibly within the loadTable method that I see referenced up there), call
GridView1.DataBind();
That should refresh the data in the grid.
After your comments, I see that you're not using the NewValues collection in the GridViewUpdateEventArgs parameter to get the actual incoming, updated field values. Try this:
String StartTime = e.NewValues["StartTime"].ToString();
String EndTime = e.NewValues["EndTime"].ToString();
String id = e.Keys[0].ToString();
Note that these variables are strings now, not TextBoxs, so you don't need to add ".Text" on them when you add them as parameters.
Handle the postback, basically if you fill the grid view in each postback you are re filling the gridview with old data, that's why you retrieve data with no changes (remember after Update button this trigger a postback). So, in case this is your case, try this.
if(!this.IsPostback)
{
(Method that fills your GridView)
}

show data in outside textbox from selected row in gridview

I am having a grid view created by using template fields. I inserted a link button using template fields in the grid view.
There are 4 textboxes outside the GridView.. i want to select the row on link button's click and put the selected row's data in text boxes. I am using a row command even for this but its not working ... the syntax i am using is .:
<asp:GridView ID="gview" AutoGenerateColumns="False" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" onrowcommand="gview_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Book Name">
<ItemTemplate>
<%#Eval("book_name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Author">
<ItemTemplate>
<%#Eval("book_author") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Publisher">
<ItemTemplate>
<%#Eval("book_Publisher") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Price">
<ItemTemplate>
<%#Eval("book_Price") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:LinkButton ID="lnkDet" CommandName="cmdBind" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" runat="server" CausesValidation="false">View Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
and Code behind file :
protected void gview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "cmdBind")
{
LinkButton lb = (LinkButton)e.CommandSource;
int index = Convert.ToInt32(lb.CommandArgument);
//Bind values in the text box of the pop up control
txt_name.Text = gview.Rows[index].Cells[0].Text;
txt_author.Text = gview.Rows[index].Cells[1].Text;
txt_price.Text = gview.Rows[index].Cells[2].Text;
}
}
Can anyone tell me how to do this.
I think this works:
protected void gview_RowCommand(object sender, GridViewCommandEventArgs e){
if (e.CommandName == "cmdBind")
{
int index = Convert.ToInt32(e.CommandArgument);
//Bind values in the text box of the pop up control
txt_name.Text = gview.Rows[index].Cells[0].Text;
txt_author.Text = gview.Rows[index].Cells[1].Text;
txt_price.Text = gview.Rows[index].Cells[2].Text;
}}
Attempting it the way you are is not impossible, but it may be easier to just use the in built select buttons for each row. That way you can just use the SelectedIndexChanged event of the gridview:
protected void gview_SelectedIndexChanged(object sender, EventArgs e)
{
txt_name.Text = gview.SelectedRow.Cells[0].Text;
txt_author.Text = gview.SelectedRow.Cells[1].Text;
txt_price.Text = gview.SelectedRow.Cells[2].Text;
}

Query regarding the nested grid views in asp.net/C#

I have defined a nested grid view in the following way.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" GridLines="None">
<Columns>
<asp:BoundField DataField="Date Of Transaction" HeaderText="Date Of Transaction"
SortExpression="Date Of Transaction" />
<asp:BoundField DataField="Invoice Number" HeaderText="Invoice Number" SortExpression="Invoice Number" />
<asp:BoundField DataField="totalAmount" HeaderText="totalAmount" ReadOnly="True"
SortExpression="totalAmount" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" ShowHeader="false" GridLines="None" OnRowDataBound="gridView2_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Download" OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ComponentDBConnectionString %>"
SelectCommand="SelectUserPreviousHistory" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="XYZZ" Name="userName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
The screenshot of the output is here. As you can see i have a "Download" button in each row of the child gridview (i.e., gridView2) but I want the download button to be last column but .net is rendering it to be the first column.
How can I do it?
More over gridview2 datasource is arraylist. Here is the code
gridView2.DataSource = titlesArrayList;
gridView2.DataBind();
Please help me
Thanks in anticipation
Why don't you simply add a Label before the Donwload-Button in the ItemTemplate? You could set the Label's Text in RowDataBound(gridView2_DataBound).
Edit: to show the header columns of the nested gridview in the header of the outer gridview, you could set ShowHeader="false" in the inner grid and use a HeaderTemplate with two labels for "Software Titles" and "Download here" and appropriate CSS-Styles to fit to the inner grid.
Edit:
Here is a working test-page. Pick the parts you didn't understand:
aspx:
<asp:GridView ID="GrdTransaction" runat="server" OnRowDataBound="GrdTransaction_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DateOfTransaction" HeaderText="Date Of Transaction"
SortExpression="DateOfTransaction" />
<asp:TemplateField>
<HeaderTemplate>
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td><asp:Label ID="LblFileNameHeader" Text="File-Name" runat="server" /></td><td><asp:Label ID="LblDownloadHeader" Text="Download file" runat="server" /></td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:GridView ID="GrdDocument" runat="server" ShowHeader="false" GridLines="None" AutoGenerateColumns="false"
OnRowCommand="GrdDocument_RowCommand" OnRowDataBound="GrdDocument_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="LblFileName" Text='<%# Eval("Doc")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="BtnDownload" runat="server" CommandArgument='<%# Eval("Doc")%>' CommandName="Download" Text="Download" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Codebehind(converted from vb.net to c#):
public class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
this.GrdTransaction.DataSource = GetOuterGridSource();
this.GrdTransaction.DataBind();
}
}
private DataTable GetOuterGridSource()
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("DateOfTransaction", typeof(DateTime)));
DataRow row = tbl.NewRow();
row["ID"] = 1;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
return tbl;
}
private DataTable GetNestedGridSource()
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Doc", typeof(string)));
DataRow row = tbl.NewRow();
row["ID"] = 1;
row["Doc"] = "Smart Defrag";
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["Doc"] = "Visio Viewer";
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["Doc"] = "Rapid Typing";
tbl.Rows.Add(row);
return tbl;
}
protected void GrdTransaction_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
dynamic row = ((DataRowView)e.Row.DataItem).Row;
dynamic GrdDocument = (GridView)e.Row.FindControl("GrdDocument");
GrdDocument.DataSource = GetNestedGridSource();
GrdDocument.DataBind();
GrdDocument.RowCommand += GrdDocument_RowCommand;
}
}
protected void GrdDocument_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
dynamic row = ((DataRowView)e.Row.DataItem).Row;
dynamic LblFileName = (Label)e.Row.FindControl("LblFileName");
LblFileName.Text = row("Doc").ToString;
}
}
protected void GrdDocument_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "Download") {
dynamic docName = e.CommandArgument.ToString();
}
}
public WebForm1()
{
Load += Page_Load;
}
}
I have set the LblFileName's Text poperty in GrdDocument_RowDataBound. That is redundant because i've always used eval on the aspx-page. I wanted to show both ways for the sake of completeness.
This is result:
in your gridView2, set AutoGenerateColumns="False" and add a asp:BoundField before the asp:TemplateField
Are you sure there is no missing code in your snippet?
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" ShowHeader="false" GridLines="None" OnRowDataBound="gridView2_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="" DataField="ToString" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Download" OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Editable Gridview with code behind data source from ODBC

I am trying to make a small gridview that lists the results of a query against a non standard SQL db, and with this information I want the user to be able to edit a column or two to update the data in the db. I know this is easy with an sqldatasource control but I lack that luxury and I am having trouble switching from my itemTemplates in the gridview to the edittemplates when I fire the gridview's edit event.
any pointers?
some code:
<asp:GridView ID="ExamEditGridView" runat="server" OnRowEditing="EditExam" OnRowUpdating="SaveEdit"
DataKeyNames="iproc_code" AllowSorting="true" AutoGenerateColumns="false" AutoGenerateEditButton="true">
<HeaderStyle BackColor="#006633" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<Columns>
<asp:TemplateField HeaderText="Exam Title">
<ItemTemplate>
<asp:Label ID="col1" runat="server" Text='<%# Bind("rpt_descrip") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="EditText" runat="server" Text='<%# Bind("rpt_descrip") %>' Visible="false" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Short Description" DataField="short_descrip" />
<asp:BoundField HeaderText="Description" DataField="descrip" />
<asp:BoundField HeaderText="Sched Note" DataField="sched_note" />
</Columns>
</asp:GridView>
code behind:
(the query is just a simlpe select statement)
string mod_id = modSelect.SelectedValue;
string query = qry + mod_id;
using (OdbcConnection connection = new OdbcConnection(DbConnectionString))
{
OdbcDataAdapter adapter = new OdbcDataAdapter(query, connection);
DataTable dt = new DataTable();
connection.Open();
adapter.Fill(dt);
ExamEditGridView.DataSource = dt;
ExamEditGridView.DataBind();
}
the gridview is databound when a dropdown lists index changes, which gives me the mod_id for the query
I ended up getting it working, I didn't realize I had to set the gridview's editindex value and redatabind to toggle edit mode
code:
protected void EditExam(object sender, GridViewEditEventArgs e)
{
ExamEditGridView.EditIndex = e.NewEditIndex;
ExamEditGridView.DataSource = Session["data"];
ExamEditGridView.DataBind();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
ExamEditGridView.EditIndex = -1;
ExamEditGridView.DataSource = Session["data"];
ExamEditGridView.DataBind();
}

Resources