I have a GridView1, which I am binding from code behind. The one of the columns in the GridView depends on Label1.Text as follows:
SqlCommand comd = new SqlCommand("SELECT Location_Profile_Name, " + Label1.Text + " FROM Home_Profile_Master", con);
SqlDataAdapter da = new SqlDataAdapter(comd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
The aspx code for the same is :
<asp:TemplateField HeaderText="Location_Profile_Name"
SortExpression="Location_Profile_Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("Location_Profile_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Home_Profile" SortExpression="Label10">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Home_Profile") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
I am getting an error in the aspx page as: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Home_Profile'.
I am not able to figure out what the mistake is. Kindly Help...! thank you.
you missed 'Home_Profile' in the query.
SqlCommand comd = new SqlCommand("SELECT Location_Profile_Name," + Label1.Text + " as Home_Profile FROM Home_Profile_Master", con);
you shuld have Home_Profile column in data table try this
SqlCommand comd = new SqlCommand("SELECT Location_Profile_Name,Home_Profile, " + Label1.Text + " FROM Home_Profile_Master", con);
Related
The part of the code am working on is vulnerable to stored XSS. Below is the code.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_OnRowDeleting" OnPageIndexChanging="GridView1_PageIndexChanging" Width ="1000px" class="grid">
<Columns>
<asp:TemplateField HeaderText="User Name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Text='<%#Eval("Uname") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Name" runat="server" Text='<%#Eval("Uname") %>'></asp:TextBox> //this is the line vulnerable to XSS
</EditItemTemplate>
</asp:TemplateField> </columns>
</asp:GridView>
code behind
DataTable dt = new DataTable();
try
{
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("Select Uid,Uname,Utype,Uemail,ClientName,ProjectName,Ulog from usrtable where ClientName='" + clientname + "' and Utype='Admin' or ClientName='" + clientname + "'and Utype='Normal'", con);
adapt.Fill(dt);
con.Close();
}
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Can you let me know where am going wrong. Is it on the client side where I am binding the column names to textbox in gridview?
I have did a Edit/Update/Delete/Cancel in the gridbox. All the functionlaities are working fine. Except Updating.
When I Click, I get an error stating,
NullReferenceException was unhandled by the user code.
Object Reference not set to an instance of an object
Here is the Code for updating the data's
protected void Show_Grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = int.Parse(Show_Grid.DataKeys[e.RowIndex].Value.ToString());
TextBox title_txt = (TextBox)Show_Grid.Rows[e.RowIndex].FindControl("Title");
TextBox Desc_Txt = (TextBox)Show_Grid.Rows[e.RowIndex].FindControl("Description");
DropDownList Prior_Drop = (DropDownList)Show_Grid.Rows[e.RowIndex].FindControl("Priority");
Update_todo(id, title_txt.Text, Desc_Txt.Text, Prior_Drop.SelectedValue);
Show_Grid.EditIndex = -1;
BindData();
}
private void Update_todo(int id, string title, string desc, string prior)
{
string source = "Data Source=.\\SQLEXPRESS;AttachDbFilename=...//...//..//..//tododb.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection dbconnect = new SqlConnection(source);
string query = "UPDATE todolist SET Title='" + title + "', Description='" + desc + "', Priority='" + prior + "' WHERE id =" + id + " ";
SqlCommand cmd = new SqlCommand(query, dbconnect);
dbconnect.Open();
cmd.ExecuteNonQuery();
}
In the Gridbox, while editing i gave TextBox with SingleLine for Title, TextBox with Multiline for Description & DropDown for Priority.
I get the error in this line
Update_todo(id, title_txt.Text, Desc_Txt.Text, Prior_Drop.SelectedValue);
Grid view markup
<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="Desc_Txt" runat="server" Text='<%# Eval("Description") %>'
TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Priority">
<EditItemTemplate>
<asp:DropDownList ID="Prior_Drop" runat="server"
SelectedValue='<%# Eval("Priority") %>'>
<asp:ListItem></asp:ListItem>
<asp:ListItem>High</asp:ListItem>
<asp:ListItem>Medium</asp:ListItem>
<asp:ListItem>Low</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Priority") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Operation" ShowDeleteButton="True"
ShowEditButton="True" />
</Columns>
</asp:GridView>
You are either not getting one or all of the controls title_txt, Desc_Txt or Prior_Drop
Check if they are null or not before accessing them
You can have a check before calling update like this, however you have to make sure that it does not break your functionality in any way
if(title_txt!=null && Desc_Text!=null && Prior_Drop!=null)
{
Update_todo(id, title_txt.Text, Desc_Txt.Text, Prior_Drop.SelectedValue);
Show_Grid.EditIndex = -1;
BindData();
}
Update
The mistake you are doing is, you are accessing the controls with wrong ids, use this and it will work
TextBox title_txt = (TextBox)Show_Grid.Rows[e.RowIndex].FindControl("title_txt");
TextBox Desc_Txt = (TextBox)Show_Grid.Rows[e.RowIndex].FindControl("Desc_Txt");
DropDownList Prior_Drop = (DropDownList)Show_Grid.Rows[e.RowIndex].FindControl("Prior_Drop");
I want to display the result according to following table
conn.Open();
string str = "SELECT agent.name, COALESCE(SUM(sale),0) AS totalSales
FROM agent LEFT OUTER JOIN sale
ON agent.name = sale.name GROUP BY agent.name";
SqlCommand cmd = new SqlCommand(str, conn);
SqlDataAdapter da = new SqlDataAdapter(str,conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataList1.DataSource = ds;
DataList1.DataBind();
conn.Close();
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow" CssClass="container" CellSpacing="2">
<ItemTemplate><asp:Label ID="Label1" runat="server" Style="font-family:Britannic;" Text='<%# Eval("Name") %>'></asp:Label>
<asp:Label ID="Label5" runat="server" Text="totalSales"></asp:Label></ItemTemplate>
</asp:DataList>
i write this code in server side but it dint work and it gives me error like
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'totalSales'
Try this
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow" CssClass="container" CellSpacing="2">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Style="font-family:Britannic;" Text='<%# Eval("Name") %>'></asp:Label>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("totalSales") %>'></asp:Label>
</ItemTemplate>
</asp:DataList>
How to insert gridview each row value into database.I use below code but null values are pass in strings.
foreach (GridViewRow gvrow in GridView1.Rows)
{
con.Open();
string datetime = Request.Form["txtdate"];
str += GridView1.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
Id += gvrow.Cells[0].Text;
fName += gvrow.Cells[1].Text;
FaName += gvrow.Cells[2].Text;
LName += gvrow.Cells[3].Text;
attendance += gvrow.Cells[4].Text;
remarks += gvrow.Cells[5].Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [first].[dbo].[Staff_Attendance]([Id],[Department],[Date],[First_name],[Father_name],[Last_name],[Attendance],[Remarks]) VALUES(#Id, #Department, #Date, #First_name, #Father_name, #Last_name, #Attendance, #Remarks)", con);
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#Department", DropDownList1.SelectedItem .ToString ());
cmd.Parameters.AddWithValue("#Date", datetime.ToString());
cmd.Parameters.AddWithValue("#First_name", fName);
cmd.Parameters.AddWithValue("#Father_name", FaName);
cmd.Parameters.AddWithValue("#Last_name", LName);
cmd.Parameters.AddWithValue("#Attendance", attendance);
cmd.Parameters.AddWithValue("#Remarks", remarks);
cmd.ExecuteNonQuery();
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Data Have Been Saved')", true);
con.Close();
}
Gridview code:-
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" onpageindexchanging="GridView1_PageIndexChanging"
PageSize="5" AutoGenerateColumns="False" DataKeyNames ="srno">
<PagerSettings FirstPageText="First" LastPageText="Last"
Mode="NumericFirstLast" PageButtonCount="5" />
<Columns >
<asp:TemplateField HeaderText="Sr.No.">
<ItemTemplate>
<asp:Label ID="lblsrno" runat="server" Text='<%#Eval("srno") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFname" runat="server" Text='<%#Eval("first_name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Father Name">
<ItemTemplate>
<asp:Label ID="lblFaName" runat="server" Text='<%#Eval("father_name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLName" runat="server" Text='<%#Eval("last_name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attendance">
<ItemTemplate>
<asp:DropDownList ID="ddlDesignation" runat="server" Width ="80px">
<asp:ListItem Text ="--Select--" ></asp:ListItem>
<asp:ListItem Text ="P"></asp:ListItem>
<asp:ListItem Text ="A"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:DropDownList ID="ddlRemark" runat="server" Width ="80px">
<asp:ListItem Text ="--Select--" ></asp:ListItem>
<asp:ListItem Text ="Paid Leave"></asp:ListItem>
<asp:ListItem Text ="Unpaid Leave"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In database it stored null values
You can try using following code, have written a sample code ,
foreach (GridViewRow row in GridView1.Rows) {
Label lblFname = (Label)row.FindControl("lblFname");
Label lblFaName = (Label)row.FindControl("lblFaName");
Label lblLName = (Label)row.FindControl("lblLName");
DropDownList ddl_att = (DropDownList)row.FindControl("ddlDesignation");
DropDownList ddl_rmk = (DropDownList)row.FindControl("ddlRemark");
dataInsert(lblFname.Text,lblFaName.Text,ddl_att.SelectedValue);
}
public void dataInsert(string First_name,string Father_name,string Attendance)
{
using (SqlConnection con = new SqlConnection(conn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "yourInsertQuery";
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#First_name", First_name);
cmd.Parameters.AddWithValue("#Father_name", Father_name);
cmd.Parameters.AddWithValue("#Attendance", Attendance);
...
...
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
Also you can save data into datatable and if your DataTable schema and table schema are matched, then using SqlBulkCopy you can do bulk insert into your database.
First You can find the controls in gridview then get Text. May be your problem will solve.
fName += ((Label)gvrow.Cells[1].FindControl("lblFname")).Text;
FaName +=((Label)gvrow.Cells[2].FindControl("lblFaName").Text);
LName += ((Label)gvrow.Cells[3].FindControl("lblLName")).Text;
attendance +=((DropDownList)gvrow.Cells[4].FindControl("ddlDesignation")).SelectedItem.Text;
remarks += ((DropDownList)gvrow.Cells[5].FindControl("ddlRemark")).SelectedItem.Text;
This question already exists:
how to show data in gridview from arraylist in asp.net?
Closed 8 years ago.
I have a database where there is userid, problemname and status column. I am retrieving this data from database in an ArrayList and returning it. Now to show in GridView I have taken a DataTable and in the DataTable I have put three columns and I just want to show my data that is saved in the ArrayList in these columns by making one row.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
ArrayList myArrayList = ConvertDataSetToArrayList();
// Display each item of ArrayList
DataTable dt = new DataTable();
dt.Columns.Add("User Id");
dt.Columns.Add("Problem Name");
dt.Columns.Add("Status");
foreach (Object row in myArrayList)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["User Id"] = ((DataRow)row)["userid"].ToString();
dt.Rows[dt.Rows.Count - 1]["Problem Name"] = ((DataRow)row) ["problemname"].ToString();
dt.Rows[dt.Rows.Count - 1]["Status"] = ((DataRow)row)["status"].ToString();
}
GridView1.DataSource =dt;
GridView1.DataBind();
}
public ArrayList ConvertDataSetToArrayList()
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT userid,problemname,status FROM problemtable", objsqlconn);
cmd.ExecuteNonQuery();
cmd.CommandType = CommandType.Text;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in myDataSet.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
objsqlconn.Close();
return myArrayList;
}
Here is my html:
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="cdd">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
Why is my data is not showing in my GridView?
You need to bind your data to specific controls in your gridview. For example, you need to have labels in your gridview itemtemplate to bind your data to. Here is an example:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="cdd">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Id">
<ItemTemplate>
<asp:Label ID="lbl_userid" runat="server" Text='<%# Eval("User Id") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Problem Name">
<ItemTemplate>
<asp:Label ID="lbl_problemname" runat="server" Text='<%# Eval("Problem Name") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="status">
<ItemTemplate>
<asp:Label ID="lbl_status" runat="server" Text='<%# Eval("Status") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I agree that an ArrayList is a poor choice, but, regardless of how you're binding the data, you need to tell the gridview what it's supposed to show. You can do this using inline tags or by using an onitemdatabound trigger. I recommend you look up some more examples of gridviews.