I have been looking all over web and testing what I think would work. I feel close but I guess not close enough. I need help pull the data in. The button click is to submit/insert data into the DB which I have not completed that part. Right now I am working on just getting data from the Gridview and need help.
The Update Button is outside the Gridview. I want end user to complete GridView then click update to submit data from Gridview to database.
Here is ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="dsSnumbers" OnRowDataBound="GridView1_RowDataBound"
GridLines="Horizontal" BackColor="White" BorderColor="#336666" BorderStyle="Double"
BorderWidth="3px">
<Columns>
<asp:TemplateField HeaderText="SerialNumber">
<ItemTemplate>
<asp:TextBox ID="TextBox1" BackColor="BurlyWood" runat="server" Text='<%# Eval("SerialNumber") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DdStatus" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept">
<ItemTemplate>
<asp:DropDownList ID="DdDept" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" RepeatLayout="Flow" RepeatDirection="Horizontal"
runat="server">
<asp:ListItem Text="Modify?" Value="1">
</asp:ListItem>
</asp:CheckBoxList>
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
<%-- <EmptyDataTemplate></EmptyDataTemplate>--%>
</asp:GridView>
And here is the .CS side
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
int RI = g1.RowIndex;
//SqlConnection con = new SqlConnection(connStr);
TextBox test = (TextBox)g1.Cells[0].FindControl("TextBox1");
TextBox test1 = (TextBox)g1.Cells[1].FindControl("TextBox1");
GridViewRow Grow = (GridViewRow)g1.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("TextBox1");
DropDownList testdd1 = (DropDownList)g1.Cells[0].FindControl("DdStatus");
DropDownList testdd2 = (DropDownList)g1.Cells[1].FindControl("DdStatus");
string test1324 = g1.Cells[1].Text;
string test2 = g1.Cells[2].Text;
string test3 = g1.Cells[3].Text;
}
}
Update:
When I run the below I can read the button click whether it is checked or not. However the textbox and dropdown still do nothing. I show ONLY rindex is pulling values. None of the others.
foreach (GridViewRow row in GridView1.Rows)
{
int rindex = row.DataItemIndex;
//string Test = ((TextBox)(row.Cells[0].Controls[0])).Text;
TextBox IDNum = (TextBox)row.FindControl("TextBox1");
string textBox1 = ((TextBox)row.FindControl("TextBox1")).Text;
string ddl1 = ((DropDownList)row.FindControl("DdStatus")).SelectedValue;
string ddl2 = ((DropDownList)row.FindControl("DdDept")).SelectedValue;
int ddl1231 = ((DropDownList)row.FindControl("DdStatus")).SelectedIndex;
int ddl1232 = ((DropDownList)row.FindControl("DdDept")).SelectedIndex;
Related
My page which to do this:
I want to connect outside dropdown list to inside of gridview dropdownlist. When selec item from outside dropdownlist, must be change inside dropdown list item automaticaly. I've tried a lot thing to change. Can you give me help. Thanks.
My ASPX page.(Don't answer connected this code)
<asp:GridView ID="GridView4" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="Kimlik" GridLines="Horizontal"
onrowdatabound="GridView4_RowDataBound" ForeColor="#333333" Visible="False">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Öd.Nu.">
<EditItemTemplate>
<asp:TextBox ID="TextBox1x" runat="server" Text='<%# Bind("Kimlik") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1x" runat="server" Text='<%# Bind("Kimlik") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Öğrenci Adı Soyadı">
<EditItemTemplate>
<asp:TextBox ID="TextBox2x" runat="server" Text='<%# Bind("OgrenciAdiSoyadi") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2x" runat="server" Text='<%# Bind("OgrenciAdiSoyadi") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Odev Sonucu">
<EditItemTemplate>
<asp:TextBox ID="TextBox3x" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1x" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ödev Sonuç Açıklaması">
<EditItemTemplate>
<asp:TextBox ID="TextBox4x" runat="server" Text='<%# Bind("SonucAciklama") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4x" runat="server" Text='<%# Bind("SonucAciklama") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
on Selected Index Change Event of Outer drop down add below code
protected void OurterDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView.Rows)
{
DropDownList innerDropdown = (DropDownList)row.FindControl("innedDropedDOwnID");
innerDropdown .ClearSelection(); //making sure the previous selection has been cleared
innerDropdown .Items.FindByValue(OurterDropDown.SelectedValue).Selected = true;
}
}
Make sure you have set AutoPostBack="true" outside DropDownList and then try this code in RowDataBound event:
protected void GridView4_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check if your row is not a Header/Footer row
if (e.Row.RowType == DataControlRowType.DataRow)
{
// get Dropdownlist from gridview
DropDownList DropDownList1x = e.Row.FindControl("DropDownList1x") as DropDownList;
// ddlouter is your outside DropDownList
DropDownList1x.Items.FindByValue(ddlOuter.SelectedValue).Selected = true;
}
}
<asp:GridView ID="GridView1" runat="server" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Add Records">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" OnClick="btnadd_Click" CommandName="insert"
Text="Insert"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete Records">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="True" OnClick="btndelete_Click" CommandName="delete"
Text="delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="id">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%#Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Client Name">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%#Bind("client_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lblemail" runat="server" Text='<%#Bind("email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Google Email">
<ItemTemplate>
<asp:Label ID="lblgemail" runat="server" Text='<%#Bind("google_email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact Number">
<ItemTemplate>
<asp:Label ID="lblcont" runat="server" Text='<%#Bind("contact_number") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="role">
<ItemTemplate>
<asp:Label ID="lblrole" runat="server" Text='<%#Bind("role") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
I have a table with 100 record
This is my Gridview I have two buttons add and delete(on Delete buttonClick particular record should be deleted from database) like, I clicked on record number 35(record number 35 should be deleted) but instead record number 1 is being deleted everytime.
public void delete()
{
foreach (GridViewRow g in GridView1.Rows)
{
Label lblname = (Label)g.FindControl("lblname");
Button btnde = (Button)g.FindControl("btndelete");
//Response.Redirect("cs.aspx");
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + lblname.Text + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
}
}
protected void btndelete_Click(object sender, EventArgs e)
{
delete();
GridView1.Visible = false;
}
This is my CS code.
It's because on delete you are deleting record using foreach loop which is not a good way to do. You could try out this:
public void delete(string Name)
{
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + Name + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
}
And on Delete button click find the particular row and send it to delete Method
protected void btndelete_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
string name = ((Label)gvr.FindControl("lblname")).Text;
delete(name);
GridView1.Visible = false;
}
Note: Also you could write your redirection inside button click event on basis of delete method return.
You can find your Label control position and get their value, then delete from database. It will work fine.
public void delete()
{
foreach (GridViewRow g in GridView1.Rows)
{
if(g.RowType == DataControlRowType.DataRow)
{
Label lblname = (Label)g.FindControl("lblname");
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + lblname.Text + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
break;
}
}
}
I have tried several so called answers for this and it has me lost. I am simply trying to default a TextBox Text value with today's date and time, but I cannot find the control when I click LinkButton with CommandName "Edit".
Here is my gridview...
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3"
DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowCommand="gvSignInRegister_RowCommand1">
<Columns>
<asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
<EditItemTemplate>
<asp:TextBox ID="txtReturned" runat="server"></asp:TextBox>
<asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
<asp:RequiredFieldValidator ID="rfv1" runat="server" SetFocusOnError="true" ValidationGroup="vg1" ControlToValidate="txtReturned" ErrorMessage="Required"></asp:RequiredFieldValidator>
<ajaxToolkit:CalendarExtender ID="ce1" runat="server" PopupButtonID="calImg" Enabled="true" Format="dd/MM/yyyy" TargetControlID="txtReturned" PopupPosition="TopRight" OnClientDateSelectionChanged="AppendTime"></ajaxToolkit:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval("DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="btnCAN" runat="server" CausesValidation="false" CommandName="Cancel" Text="CANCEL" />
<asp:Button ID="btnUPD" runat="server" ValidationGroup="vg1" CausesValidation="true" CommandName="Update" Text="UPDATE" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btnEDT" runat="server" CausesValidation="false" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>' Text="SIGN IN" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
The LinkButton btnEDT works and puts the gridview in edit mode. But in code behind I cannot find "txtReturned".
This is what I've tried so far...
protected void gvSignInRegister_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int rowIdx = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvSignInRegister.Rows[rowIdx];
if (row != null && row.RowType == DataControlRowType.DataRow)
{
TextBox tb = (TextBox)row.FindControl("txtReturned");
if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
//I've tried this too but it does not work. Interestingly, it does not crash, so cells[4] must exist!
//row.Cells[4].Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}
}
}
For some reason the rowIdx is always 0. Why? I thought a row index of 0 meant the header of the gridview control.
I've also tried using the NamingContainer that most other people have suggested in other posts, but that returns a blank (I suspect new?) GridViewRow.
ie
GridViewRow row = (GridViewRow)((GridViewRow)(e.CommandSource).NamingContainer);
UPDATE
I found this, which is exactly the problem I am having, but the solution via the RowEditing still does not find the textbox!
However the RowDataBound() solved it! Read my answer below.
The answer was in getting into the editmode version of the GridView itself and then find the control!
As per this post...
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3"
DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowDataBound="gvSignInRegister_RowDataBound">
<Columns> ...etc...
protected void gvSignInRegister_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
TextBox tb = (TextBox)e.Row.FindControl("txtReturned");
if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}
}
}
Use Container.DisplayIndex instead of Container.DataItemIndex
But I dont think you will get textBox control if you are placing it in EditItemTemplate
If your expectation is editing operation then please use the below code
HTML
<asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" OnRowEditing="gvSignInRegister_RowEditing" OnRowCancelingEdit="gvSignInRegister_RowCancelingEdit" OnRowUpdating ="gvSignInRegister_RowUpdating" GridLines="Vertical">
<Columns>
<asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
<EditItemTemplate>
<asp:TextBox ID="txtReturned" Text='<%#Bind("DateTimeReturned", "{0:dd/MM/yyyy HH:mm}")%>' runat="server"></asp:TextBox>
<asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Eval( "DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
Code Behind:
protected void gvSignInRegister_RowEditing(object sender, GridViewEditEventArgs e)
{
gvSignInRegister.EditIndex = e.NewEditIndex;
List<QuotationDetail> itemList = (List<QuotationDetail>)ViewState["ItemList"];
gvSignInRegister.DataSource = itemList;
gvSignInRegister.DataBind();
}
protected void gvSignInRegister_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
protected void gvSignInRegister_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var txtQty = (TextBox)gvSignInRegister.Rows[e.RowIndex].FindControl("txtQuantity");
decimal qty = 0;
decimal.TryParse(txtQty.Text, out qty);
if (qty < 0)
{
lblErrorSummary.InnerText = "Please provide valid Quantity";
lblErrorSummary.Visible = true;
return;
}
itemList[e.RowIndex].Quantity = qty
ViewState["ItemList"] = itemList;
gvSignInRegister.EditIndex = -1;
gvSignInRegister.DataSource = itemList;
gvSignInRegister.DataBind();
}
I'm trying get values from database to dropdownlist which is placed inside a gridview item template. I'm using gridview to take values from user. In one column I'm using dropdownlist from which user has to select an item. According to the selection its cost price will populate automatically on the other column. But I'm unable to get the values in dropdownlist and getting an error "Object reference not set to an instance of an object."
Aspx code given below:
<asp:GridView ID="gvItemList" runat="server" ShowFooter="True" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" ViewStateMode="Enabled" CssClass="newStyle9" style="text-align: center" OnRowDeleting="gvItemList_RowDeleting" OnRowDataBound="gvItemList_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Sl No" SortExpression="Id">
<ItemTemplate>
<asp:Label ID="lblId" runat="server"
Text='<%# Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item">
<ItemTemplate>
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="128px">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Required Date">
<ItemTemplate>
<asp:TextBox ID="txtRequiredDate" runat="server" />
<ajaxToolkit:CalendarExtender ID="txtRequiredDate_CalendarExtender" runat="server" Enabled="True" TargetControlID="txtRequiredDate">
</ajaxToolkit:CalendarExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Required Quantity">
<ItemTemplate>
<asp:TextBox ID="txtRequiredQuantity" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cost Price">
<ItemTemplate>
<asp:Label ID="lblCostPrice" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UoM Code">
<ItemTemplate>
<asp:Label ID="lblUomCode" runat="server">Manual</asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="AddRowButton" runat="server" Text="Add New Item"
OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Code under row databound is given below:
protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
DS_SiteDataTableAdapters.tbl_ItemTableAdapter item;
item = new DS_SiteDataTableAdapters.tbl_ItemTableAdapter();
DataTable dt = new DataTable();
dt = item.GetItem();
DropDownList ddlItem = (DropDownList)e.Row.FindControl("ddlItem");
ddlItem.DataSource = dt; //here I'm getting an error "Object reference not set to an instance of an object."
ddlItem.DataTextField = "Item";
ddlItem.DataValueField = "Item";
ddlItem.DataBind();
}
Any help is greatly appreciated!
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("ddlCountries") as DropDownList);
ddlCountries.DataSource = GetData("SELECT DISTINCT Country FROM Customers");
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Select Country"));
}
Hope this helps!
just check below condition in your method
if (e.Row.RowType == DataControlRowType.DataRow)
{ your code }
I hope it will help u
As mentioned in the comments, you are trying to use a null object, thinking that it has a referenced object.
You are doing something like this:
public class Example
{
public void MyMethod()
{
}
}
Example myExample= null;
myExample.MyMethod();
You will get "Object reference not set to an instance of an object." which is the same as NullReferenceException because you are calling a method on a reference type which is null.
You are getting Object Reference error because you are not checking for DataRow in your gridview. Because of that it is trying to find the dropdown in header where it is not present and thus you are getting Dropdown object as Null.
Add this condition to your gvItemList_RowDataBound event:-
protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Your rest code
}
}
try this you get null reference because you are not able to find ddlItem control
at line
DropDownList ddlItem = (DropDownList)e.Row.FindControl("ddlItem");
so instead you can try as below
DropDownList ddlItem = (DropDownList)GridView.Rows[rowindex].FindControl("ddlItem"))
I want to use a dropdownlist on a gridview... I have the following code from asp.net
<asp:GridView ID="grdvEventosVendedor" runat="server" AllowPaging="True"
AutoGenerateColumns="False" CellPadding="4" DatakeyNames="idCita"
EmptyDataText="No Hay Eventos Para Este Vendedor" ForeColor="#333333"
GridLines="None" AllowSorting="True"
onpageindexchanging="grdvEventosVendedor_PageIndexChanging"
onrowcommand="grdvEventosVendedor_RowCommand"
onsorting="grdvEventosVendedor_Sorting" CellSpacing="1" HorizontalAlign="Center">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"/>
<Columns>
<asp:TemplateField HeaderText="" ItemStyle-Width="35px">
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdicEvento" runat="server"
CommandArgument='<%# Eval("idCita")%>' CommandName="Edicion"
Height="32px" ImageUrl="~/img/pencil_32.png" Width="32px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="" ItemStyle-Width="35px">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server"
CommandName="Borrar"
ImageUrl="~/img/1385_Disable_16x16_72.png"
onclientclick="return confirm('¿Desea eliminar el registro?');"
CommandArgument='<%# Eval("idCita")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Cliente" HeaderText="Cliente" InsertVisible="False" ReadOnly="True" SortExpression="Cliente" ItemStyle-Width="50px" />
<asp:BoundField DataField="Empresa" HeaderText="Empresa" InsertVisible="False" ReadOnly="True" SortExpression="Empresa" ItemStyle-Width="50px"/>
<asp:BoundField DataField="Telefono" HeaderText="Telefono" InsertVisible="False" ReadOnly="True" SortExpression="Telefono" ItemStyle-Width="50px"/>
<asp:BoundField DataField="Nextel" HeaderText="Nextel" InsertVisible="False" ReadOnly="True" SortExpression="Nextel" ItemStyle-Width="50px"/>
<asp:BoundField DataField="Tipo" HeaderText="Tipo" InsertVisible="False" ReadOnly="True" SortExpression="Tipo" ItemStyle-Width="50px"/>
<asp:BoundField DataField="Descripcion" HeaderText="Descripcion" InsertVisible="False" ReadOnly="True" SortExpression="Descripcion" ItemStyle-Width="100px"/>
<asp:TemplateField HeaderText="Fecha" SortExpression="Fecha" ItemStyle-Width="50px">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Fecha", "{0:dd/MM/yyyy}")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbxFecha" runat="server" Text='<%#Bind("Fecha","{0:dd/MM/yyyy}") %>' ValidationGroup="gpEdicionAgenda">
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="HoraInicio" HeaderText="Hora" InsertVisible="False" ReadOnly="True" SortExpression="HoraInicio" ItemStyle-Width="50px"/>
<asp:BoundField DataField="Lugar" HeaderText="Lugar" InsertVisible="False" ReadOnly="True" SortExpression="Lugar" ItemStyle-Width="50px"/>
<asp:TemplateField HeaderText="Estado" ItemStyle-Width="50px">
<ItemTemplate>
<asp:DropDownList ID="dpdListEstatus" runat="server">
<asp:ListItem>Pendiente</asp:ListItem>
<asp:ListItem>Atendido</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CRM" ItemStyle-Width="25px">
<ItemTemplate>
<asp:ImageButton ID="imgBtnCRM" runat="server"
CommandArgument='<%# Eval("IdCliente")%>' CommandName="CRM"
ImageUrl="~/img/activar.png" Width="16px" Height="16px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="VM" ItemStyle-Width="25px">
<ItemTemplate>
<asp:ImageButton ID="imgBtnVerMas" runat="server"
CommandArgument='<%# Eval("IdCliente")%>' CommandName="VerMas"
ImageUrl="~/img/search.png" Width="16px" Height="16px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" Font-Size="Small" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" Font-Size="Larger" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" Font-Size="Small" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
The part where it says is the part where I want the ddl to be...
You'll might've also noticed that I use a total of 4 buttons for edit, delete, etc...
However I guess that's another story...
I want it to do a couple of things... first of, you'll notice that I have the dropdownlist with 2 values... that's because I get a datasource from a query, and those are the 2 possible values that this column can get...
So #1 should be... how can I make that the Ddl's Selected Value is the one I get from the query....
and #2 I can manually change the value of the ddl, so I want it to make a postback and update that specific row with the new value (the reason I need the postback would be so I can trigger for example a ddl ONSELECTEDINDEX CHANGED and therefore use the cs file to create a new query, update the row, and then refresh the gridview again)
I suppose that all of this might have something to do with rowcommand, just like the way the other 4 buttons work.
I'm using C# on this, so It would be helpful if you can help me using C# if you're method involves the cs file...
Thanks
You should use the OnRowDatabound event on the GridView. Like:
<asp:GridView ID="grdvEventosVendedor" OnRowDatabound="grdvEventosVendedor_RowDataBound">
<asp:TemplateField HeaderText="Estado" ItemStyle-Width="50px">
<ItemTemplate>
<asp:DropDownList ID="dpdListEstatus" runat="server" OnSelectedIndexChanged="dpdListEstatus_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Pendiente</asp:ListItem>
<asp:ListItem>Atendido</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
Then in the .cs backend code you should find the control and set it's selected value based on the dataitem values.
protected void grdvEventosVendedor_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList dpdListEstatus = e.Row.FindControl("dpdListEstatus") as DropDownList;
dpdListEstatus.SelectedValue = DataBinder.Eval(e.Row.DataItem, "FieldName").ToString();
}
}
protected void dpdListEstatus_SelectedIndexChanged(object sender, EventArgs e)
{
//your logic goes here
}
You can set the SelectedIndexChanged on your dropdown in the ASPX code and in that piece of backend code you can continue your logic.
Ow, and don't forget to set the autopostback = true on your dropdown.
You can use GridView RowDataBound event to access drop down list, similarly set selectedindexchanged event for the dropdownlist.
Refer to this link below which shows the basics of the solutions you will need
http://www.codeproject.com/Articles/53559/Accessing-a-DropDownList-inside-a-GridView
This is what I did that worked for me:
**Snippet from aspx:**
<asp:TemplateField HeaderText="RECORD_STATUS" SortExpression="RECORD_STATUS">
<EditItemTemplate>
<asp:DropDownList runat="server" ID="ddlRecStatus" SelectedIndex='<%# GetselectedRecStatus(Eval("RECORD_STATUS")) %>'
DataSource = '<%# Recs_Status %>' />
</EditItemTemplate>
</asp:TemplateField>
**Snippet from code-behind:**
protected void grdSAEdit_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Get the refernce to the list control
DropDownList ddlRecStatus = (DropDownList)(grdSAEdit.Rows[e.RowIndex].FindControl("ddlRecStatus"));
// Add it to the parameters
e.NewValues.Add("RECORD_STATUS", ddlRecStatus.Text);
}
protected string[] Recs_Status
{
get { return new string[] { "A", "E", "V", "Z" }; }
}
protected int GetselectedRecStatus(object status)
{
return Array.IndexOf(Recs_Status, status.ToString());
}