i am trying to insert into sql table using gridview header template, under the gridview rowcommand i am trying to find the control and it is not able to retrieve the value.
protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
string NetWeightConnectionStrings = ConfigurationManager.ConnectionStrings["NetWeightConnectionString"].ToString();
string query = "INSERT INTO [Net Weight Tracking] ([Date])VALUES (#Date)";
using (SqlConnection sqlConn = new SqlConnection(NetWeightConnectionStrings))
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
String Date = ((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.ParseExact(((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text, "dd/MM/yyyy", null);
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridV1.DataSource = dt;
GridV1.DataBind();
sqlConn.Close();
}
}
}
any help is much appreciated
You can try the RowDataBound Event to get the header template controls.
protected void GridView1__RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
TextBox txtControl = (TextBox)e.Row.FindControl("TextBox31");
}
}
EDIT 1
From the link shared for the GridView Mark up, TextBox31 is not in the HeaderItemTemplate, it is in EditItemTemplate. That would be the reason, you are not able to find the textbox.
<EditItemTemplate>
<asp:TextBox ID="TextBox31" runat="server" Text='<%# Bind("Field4") %>'></asp:TextBox>
</EditItemTemplate>
Related
this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.
I am getting null reference in by backend CS Code. Why is the DataTable null?
<asp:TemplateField HeaderText="Frequency" ItemStyle-Width = "150" >
<ItemTemplate>
<asp:Label ID="Frequency" runat="server" Text='<% # Eval("frequency") %>' ></asp:Label>
<asp:DropDownList ID="frequencydropdownlist" runat="server" Visible="false" ></asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="Addfrequencydropdownlist" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
</Columns>
Code Behind:
public partial class CollectionHead : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtt = new DataTable();
string conString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
SqlCommand mycommand = new SqlCommand();
mycommand.Connection = con;
mycommand.CommandText = "select ID,Frequency from FeesFrequency";
mycommand.CommandType = CommandType.Text;
mycommand.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = mycommand;
sda.Fill(dtt);
DropDownList Addfrequencydropdownlist = CollectionHead_GridView.FindControl("Addfrequencydropdownlist") as DropDownList;
Addfrequencydropdownlist.DataSource = dtt.DefaultView;// null reference exception ????????
Addfrequencydropdownlist.DataTextField = "Frequency";
Addfrequencydropdownlist.DataValueField = "ID";
Addfrequencydropdownlist.DataBind();
Update You have to databind the grid first before you can access it's footer. Therefore i would use the RowDataBound event to fill the DropDownList:
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList Addfrequencydropdownlist = (DropDownList)e.Row.FindControl("Addfrequencydropdownlist");
// ...
}
}
Old answer (might still be useful):
It is Addfrequencydropdownlist which is null after your try-cast because the NamingContainer of the DropDownList in the footer of the grid is not the grid itself but the FooterRow. So this is null causing the NullReferenceException:
CollectionHead_GridView.FindControl("Addfrequencydropdownlist")
You can use the FooterRow-property of the grid to get it's reference:
GridViewRow footer = CollectionHead_GridView.FooterRow;
DropDownList Addfrequencydropdownlist = (DropDownList)footer.FindControl("Addfrequencydropdownlist");
As an aside, i would use the as operator only if it isn't exceptional that it is null. Otherwise you're replacing a menaingful NullReferenceException with a bug in your code(in this case a NullReferenceException at the wrong place).
I would also wrap it in a if(!IsPostBack)-check to databind it only at the initial load and not on every postback if ViewState is enabled(default):
if(!IsPostBack)
{
DataTable dtt = new DataTable();
// rest of your code in Page_Load ....
}
Creating a list of users that haven't updated their job title in a Gridview. I want the list to have a dropdown filled with all the possible title selections and a button next to the dropdown. Then a person can come in and change the title in the dropdown hit the button and its updated and removed from the list.
I have all of this the way I want it to look but I'm trying to figure out how to pass the SelectedValue of the dropdown box in that row to the code behind OnClick. As you can see below the closest I can get is pass the row number in the CommandArgument. Any suggestions how I can get the SelectedValue of the dropdown of that specific row to the OnClick?
EDIT: Maybe I should be using OnRowCommand instead of OnClick?
Looks like this currently:
John Doe | DropdownList Button
Jane Doe | DropdownList Button
Joe Doe | DropdownList Button
Jeff Doe | DropdownList Button
ASPX
<asp:GridView runat="server" ID="TitleView" OnRowDataBound="TitleView_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Fullname" HeaderText="Fullname" />
<asp:TemplateField>
<ItemTemplate>
<div class="input-append"><asp:DropDownList CssClass="span5" ID="TitleList" runat="server">
</asp:DropDownList>
<asp:Button ID="lbnView" runat="server" Text="Update" CssClass="btn btn-primary" OnClick="btn_Clicked"
CommandArgument='<%# ((GridViewRow)Container).RowIndex %>'></asp:Button></div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
public void bindTitleView()
{
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"SELECT U.First + ' ' + U.Last as Fullname, U.UserID, T.Name FROM Employees U LEFT JOIN Titles T ON U.Title = T.ID WHERE U.Active = '1' AND U.Title = '92' ORDER BY Fullname ASC", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
TitleView.DataSource = myDataSet;
TitleView.DataBind();
}
}
protected void TitleView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("TitleList");
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"SELECT ID, Name FROM Titles ORDER BY Name ASC", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable myDataSet = new DataTable();
adp.Fill(myDataSet);
ddl.DataSource = myDataSet;
ddl.DataTextField = "Name";
ddl.DataValueField = "ID";
ddl.DataBind();
}
}
}
protected void btn_Clicked(object sender, EventArgs e)
{
String rowid = ((Button)sender).CommandArgument;
}
SOLUTION: The answer I approved below worked for me once I added !IsPostBack to the Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindTitleView();
}
You can do like that:
protected void btn_Clicked(object sender, EventArgs e)
{
int line = ((GridViewRow)((Button)sender).Parent.Parent).RowIndex;
DropDownList drp = ((DropDownList)TitleView.Rows[line].FindControl("TitleList"));
//Continue the method
}
In your btn_click write the following code
protected void btn_Clicked(object sender, EventArgs e)
{
Button Sample = sender as Button;
GridViewRow row = Sample.NamingContainer as GridViewRow;
DropDownList drp = row.FindControl("TitleList") as DropDownList;
//Now use drp.SelectedValue
}
}
Let me know if this isnt what you are looking for.
i try to add values in dropdownlist in gridview query works fine but it appears as this ..
gridview html
<asp:BoundField HeaderText="ApproveID" DataField="ApproveID" ></asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%#
Eval("ApproveID") %>' Visible = "false" />
<asp:DropDownList ID="DropDownList4" runat="server"
class="vpb_dropdown">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
code
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("DropDownList4") as
DropDownList);
ddlCountries.DataSource = GetData("SELECT ApproveID,ApproveType FROM
ApproveType");
ddlCountries.DataTextField = "ApproveType";
ddlCountries.DataValueField = "ApproveID";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Please select"));
//Select the Country of Customer in DropDownList
//string country = (e.Row.FindControl("lblCountry") as Label).Text;
//ddlCountries.Items.FindByValue(country).Selected = true;
}
}
values are not inside in dropdownlist ..how to show values in dropdown??
and when i debug the code it cant show me any error
getdata code
private DataSet GetData(string query)
{
string conString =
ConfigurationManager.ConnectionStrings["mydms"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
Set
DropDownList1.SelectedValue = "Some Value";
then you will get the value as default
Get data function returns null or empty value so it wont through error or exception while debugging.Your code working fine better check data in the database.
In a project I participated we returned the DataTable instead of DataSet and it was working fine with dropdowns. We had code like this:
if( ds.Tables.Count == 1)
return ds.Tables[0];
else
return new DataTable();
Besides I would change the way of databinding. In my opinion using ObjectDataSource is a better approach becuase the event is called only when the data is needed and you don't have to do checks like this:
if (e.Row.RowType == DataControlRowType.DataRow)
After your last comment you should check if the DataSet contains the record you want ot set as selected:
if (ddlCountries.Items.FindByValue(country) != null)
{
ddlCountries.Items.FindByValue(country).Selected = true;
}
I have a GridView containing data extracted from two TextBoxes on click of a button. I want the following functionalities to be implemented in the Gridview:
1) I want to be able to Edit the data in this GridView.
2) I should also be able to Delete the rows from the GridView.
3) Finally, when I click on another Submit button, all the rows from the Gridview should be saved in the database.
Its a web-based ASP.NET application coded using C# (Visual Studio 2010), and uses SQL Server 2005. How can I make changes to the below code to implement the above specified functionality?
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["constring"]);
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
dt = Session["data_table"] as DataTable;
}
}
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
if (dt == null)
{
dt = new DataTable();
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("City");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
Session["data_table"] = dt;
}
DataRow dr = dt.NewRow();
dr[0] = txtName.Text;
dr[1] = txtCity.Text;
dt.Rows.Add(dr);
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
protected void btnDisplay_Click(object sender, EventArgs e)
{
ds.Clear();
da = new SqlDataAdapter("insert into PRACT values(#name, #city)", con);
con.Open();
da.Fill(ds);
gv.DataSource = ds;
gv.DataBind();
con.Close();
}
}
Well on your aspx page I would recommend you to do that:
<asp:GridView runat="server" id="gvDisplay" OnRowCommand="grid_OnRowCommand">
<Columns>
<TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtNameGrid" Text='<%#DataBinder.Eval(Container.DataItem, "Name")%>'/>
</ItemTemplate>
</TemplateField>
<TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtCityGrid" Text='<%#DataBinder.Eval(Container.DataItem, "City")%>'/>
</ItemTemplate>
</TemplateField>
<TemplateField>
<ItemTemplate>
<asp:Button runat="server" id="btnDeleteGrid" Text = "Delete" CommandArgument='<%#Eval(Container.DataItem, "YourIDColumn")%>' CommandName="DeleteRow"/>
</ItemTemplate>
</TemplateField>
</Columns>
</asp:GridView>
I recommend you to create a new column in your DataTable, this column will be the ID of each register.
Well, you add registers to this DataTable on your page, so you will need to create a session of type int and each time the event btnTextDisplay_Click is called you must increase this int Session and set it's value to the DataTable's Column ID.
The grid's attribute, OnRowCommand, is the event that will be called when you click on the button btnDeleteGrid. The code of this event comes below:
protected void grid_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "DeleteRow")
{
foreach(DataRow row in dt.Rows)
{
if(Convert.ToInt32(row["YourColumnID"]) == Convert.ToInt32(e.CommandArgument))
row.Delete();
}
dt.AcceptChanges();
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
}
Your event that will save the registers should be like that.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach(DataRow row in dt.Rows)
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["constring"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO YOUR_TABLE_NAME (NAME, CITY) VALUES (" + row["Name"].ToString() + "," + row["City"].ToString() + ")";
int numRegs = cmd.ExecuteNonQuery();
}
}
I really expect I helped.
I can't test my code and I'm not so good on work with DataTables, so if there's any problem with my code, just let me know.
I think it will be more efficient if you use Bulk Inserts to realize the inserts. Search for how to make it, it's pretty cool and quick.
And also try to use Stored Procedures, because it's safer than use direct command texts. Using them will prevent SQL Injection.
Best regards.