How to save gridview each row value in table? - c#

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;

Related

Dropdownlist displaying two gridviews

I currently have a drop down list that on selected index changed it displays data in a GridView based of the value of the drop down list. However, it is displaying the data in the existing GridView and then displaying another gridview next to the existing one with the exact information. I am just trying to display the data in the existing open.
C# Code:
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
DataTable table = new DataTable();
using (SqlConnection con = new SqlConnection(#"Data Source=
(local)\;Initial Catalog=SmallBatch;Integrated Security=True;"))
{
con.Open();
SqlDataAdapter DataAdapter = new SqlDataAdapter(string.Format("SELECT Item.ItemID, Item.ItemDesc, Stock_Take_Item.BarQuantity, Stock_Take_Item.StorageQuantity FROM Item INNER JOIN Stock_Take_Item ON Item.ItemID = Stock_Take_Item.ItemID INNER JOIN Stock_Take ON Stock_Take_Item.StockTakeIDNew = Stock_Take.StockTakeIDNew where Stock_Take.Username = '" + DropDownList1.SelectedValue + "'"), con);
DataAdapter.Fill(table);
}
GridView1.DataSource = table;
GridView1.DataBind();
}
}
Existing Gridview:
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="Item ID" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="itemIDAdmin" Text='<%# Eval("ItemID")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="itemDescAdmin" Text='<%# Eval("ItemDesc")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bar Quantity" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="barQuantityAdmin" Text='<%# Eval("BarQuantity")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Storage Quantity" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="storageQuantityAdmin" Text='<%# Eval("StorageQuantity")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

How to overcome Cross Site Scripting vulnerability in Asp.net c#

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?

Unable to bind multiple dropdownlist in gridview on editing a row

I've two columns Customer Type and File Frequency in the gridview. When the grid is in normal mode I show the values using label. On editing the row, those two columns become dropdowns. I bind the dropdowns using OnRowDataBound="RowDataBound". But, Only first dropdown(whichever first written in the method) in the RowDataBound method getting bind on the edit mode.
.aspx
<asp:GridView ID="gvManageCustomers" DataKeyNames="Ship_To" runat="server" AutoGenerateColumns="False"
OnRowEditing="EditCustomer" OnRowDataBound="RowDataBound" OnRowUpdating="UpdateCustomer"
OnRowCancelingEdit="CancelEdit" CssClass="table table-bordered table-condensed">
<Columns>
<asp:TemplateField HeaderText="Customer Type">
<ItemTemplate>
<asp:Label ID="lblCustType" runat="server" Text='<%# Eval("Customer_Type")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblCustType" runat="server" Text='<%# Eval("Customer_Type")%>' Visible="false">
</asp:Label>
<asp:DropDownList ID="ddlgvCustomerType" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Frequency">
<ItemTemplate>
<asp:Label ID="lblFileFreq" runat="server" Text='<%# Eval("FileFrequency")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblFileFreq" runat="server" Text='<%# Eval("FileFrequency")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddlgvFileFreq" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
.cs
public DataTable FetchCustomerType()
{
string sql = "select distinct Customer_TypeID,Customer_Type from tbl_CustomerType";
SqlDataAdapter da = new SqlDataAdapter(sql, constr);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
public DataTable FetchFileFrequency()
{
string sql = "SELECT distinct FileFrequency_ID,FileFrequency FROM [tbl_FileFrequency]";
SqlDataAdapter da = new SqlDataAdapter(sql, constr);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlgvFileFreq = (DropDownList)e.Row.FindControl("ddlgvFileFreq"); //getting binded
ddlgvFileFreq.DataSource = FetchFileFrequency();
ddlgvFileFreq.DataTextField = "FileFrequency";
ddlgvFileFreq.DataValueField = "FileFrequency_ID";
ddlgvFileFreq.DataBind();
ddlgvFileFreq.Items.FindByValue((e.Row.FindControl("lblFileFreq") as Label).Text).Selected = true;
DropDownList ddlgvCustomerType = (DropDownList)e.Row.FindControl("ddlgvCustomerType");
ddlgvCustomerType.DataSource = FetchCustomerType();
ddlgvCustomerType.DataTextField = "Customer_Type";
ddlgvCustomerType.DataValueField = "Customer_TypeID";
ddlgvCustomerType.DataBind();
ddlgvCustomerType.Items.FindByValue((e.Row.FindControl("lblCustType") as Label).Text).Selected = true;
}
}
}
catch (Exception ex)
{
//log error
errorlog.WriteErrorLog(ex.ToString());
}
}
The problem is in this line, it trows an exeption. That's why only the topmost binding would work.
ddlgvFileFreq.Items.FindByValue((e.Row.FindControl("lblFileFreq") as Label).Text).Selected = true;
But it looks like you want the DropDownList to have the correct SelectedValue. This is how you can do that.
DataRowView row = e.Row.DataItem as DataRowView;
DropDownList ddlgvFileFreq = (DropDownList)e.Row.FindControl("ddlgvFileFreq");
ddlgvFileFreq.DataSource = FetchFileFrequency();
ddlgvFileFreq.DataTextField = "FileFrequency";
ddlgvFileFreq.DataValueField = "FileFrequency_ID";
ddlgvFileFreq.DataBind();
try
{
ddlgvFileFreq.SelectedValue = row["FileFrequency_ID"].ToString();
}
catch
{
}
DropDownList ddlgvCustomerType = (DropDownList)e.Row.FindControl("ddlgvCustomerType");
ddlgvCustomerType.DataSource = FetchCustomerType();
ddlgvCustomerType.DataTextField = "Customer_Type";
ddlgvCustomerType.DataValueField = "Customer_TypeID";
ddlgvCustomerType.DataBind();
try
{
ddlgvCustomerType.SelectedValue = row["Customer_TypeID"].ToString();
}
catch
{
}
<asp:TemplateField HeaderText="Customer Type">
<ItemTemplate>
<asp:Label ID="lblCustType" runat="server" Text='<%# Eval("Customer_Type")%>'></asp:Label>
<asp:Label ID="lblCustTypeID" runat="server" Visible="false" Text='<%# (Eval("Customer_TypeID")) %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlgvCustomerType" runat="server" DataSource="<%# FetchCustomerType() %>" DataValueField="Customer_TypeID" DataTextField="Customer_Type" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Frequency">
<ItemTemplate>
<asp:Label ID="lblFileFreq" runat="server" Text='<%# Eval("FileFrequency")%>'></asp:Label>
<asp:Label ID="lblFileFreqID" runat="server" Visible="false" Text='<%# (Eval("FileFrequency_ID")) %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlgvFileFreq" runat="server" DataSource="<%# FetchFileFrequency() %>" DataValueField="FileFrequency_ID" DataTextField="FileFrequency" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
In onRowEditing Event
((DropDownList)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("ddlgvCustomerType")).SelectedValue = ((Label)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("lblCustTypeID")).Text;
((DropDownList)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("ddlgvFileFreq")).SelectedValue = ((Label)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("lblFileFreqID")).Text;

Save Grid View Textbox Data to database

I am trying to save grid view text box value and two other text box that are filled by user that are Total Marks and Marks Scored to data base am not sure how to pass back the values of that textboxs to data base on one click of submit
DB where the value to be saved are
Studentname RegNo TotalMarks Marksscored
asdsa 22 125 22
My Gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Names">
<ItemTemplate>
<asp:TextBox ID="txtStudent_Name" runat="server" Text='<%# Eval("StudentFirstName") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Register Number">
<ItemTemplate>
<asp:TextBox ID="txtreg_number" runat="server" Text='<%# Eval("StudentRegID") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Marks">
<ItemTemplate>
<asp:TextBox ID="txttotal_marks" runat="server" Text='' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Marks Scored">
<ItemTemplate>
<asp:TextBox ID="txtmarks_scored" runat="server" Text='' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
DataTable dt = new DataTable();
DataRow row = dt.NewRow();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox txtUsrId=(TextBox)GridView1.Rows[i].FindControl("Your textbox id");
string UserID = txtUsrId.Text;
string q="insert into details (name) values('"+UserID+"')";
SqlCommand cmd = new SqlCommand(q, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
}

Why is my data not showing in my GridView? [duplicate]

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.

Categories