I have created a webform which imports the excel file into gridview.
Now I want to add checkbox control to each header (along with the header text).
Below is the code where I am
1. Importing the excel data.
2. Store it into a datatable
3. Creating gridview dynamically
4. Binding the data into the gridview.
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
If FileUpload1.HasFile Then
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Dim FolderPath As String = ConfigurationManager.AppSettings("FolderPath")
Dim FilePath As String = Server.MapPath(FolderPath + FileName)
FileUpload1.SaveAs(FilePath)
Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text)
End If
End Sub
Private Sub Import_To_Grid(ByVal FilePath As String, ByVal Extension As String, ByVal isHDR As String)
Dim conStr As String = ""
Select Case Extension
Case ".xls"
conStr = ConfigurationManager.ConnectionStrings("Excel03ConString").ConnectionString
Exit Select
Case ".xlsx"
conStr = ConfigurationManager.ConnectionStrings("Excel07ConString").ConnectionString
Exit Select
End Select
conStr = String.Format(conStr, FilePath, isHDR)
Dim connExcel As New OleDbConnection(conStr)
Dim cmdExcel As New OleDbCommand()
Dim oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmdExcel.Connection = connExcel
connExcel.Open()
Dim dtExcelSchema As DataTable
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim SheetName As String = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
connExcel.Close()
connExcel.Open()
cmdExcel.CommandText = "SELECT * From [" & SheetName & "]"
oda.SelectCommand = cmdExcel
oda.Fill(dt)
connExcel.Close()
Dim GridView1 As GridView = New GridView
GridView1.AutoGenerateColumns = False
For i As Integer = 0 To dt.Columns.Count - 1
Dim boundfield As BoundField = New BoundField
boundfield.DataField = dt.Columns(i).ColumnName.ToString()
boundfield.HeaderText = dt.Columns(i).ColumnName.ToString()
GridView1.Columns.Add(boundfield)
Next
GridView1.DataSource = dt
GridView1.DataBind()
Panel1.Controls.Add(GridView1)
End Sub
All working fine. But when it comes to adding checkbox to header text, I am completely blank. Kindly suggest the solution or any other approach I can use.
No Comments :(
Anyway, I have done it myself. It was pretty simple. I was thinking too much. Here's the code.
ASPX:
<form id="form1" runat="server">
<div>
Import Excel File:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="btnUpload_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Has Header ?" />
<asp:RadioButtonList ID="rbHDR" runat="server">
<asp:ListItem Text = "Yes" Value = "Yes" Selected = "True" >
</asp:ListItem>
<asp:ListItem Text = "No" Value = "No"></asp:ListItem>
</asp:RadioButtonList>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
</form>
Codebehind:
Private Sub Import_To_Grid(ByVal FilePath As String, ByVal Extension As String, ByVal isHDR As String)
Dim conStr As String = ""
Select Case Extension
Case ".xls"
'Excel 97-03
conStr = ConfigurationManager.ConnectionStrings("Excel03ConString") _
.ConnectionString
Exit Select
Case ".xlsx"
'Excel 07
conStr = ConfigurationManager.ConnectionStrings("Excel07ConString") _
.ConnectionString
Exit Select
End Select
conStr = String.Format(conStr, FilePath, isHDR)
Dim connExcel As New OleDbConnection(conStr)
Dim cmdExcel As New OleDbCommand()
Dim oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmdExcel.Connection = connExcel
connExcel.Open()
Dim dtExcelSchema As DataTable
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim SheetName As String = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
connExcel.Close()
connExcel.Open()
cmdExcel.CommandText = "SELECT * From [" & SheetName & "]"
oda.SelectCommand = cmdExcel
oda.Fill(dt)
connExcel.Close()
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Protected Sub GridView1_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowCreated
' Check the header type
If e.Row.RowType = DataControlRowType.Header Then
Dim litHeader As Literal
Dim txtSearch As CheckBox
' loop through each cell
For i As Integer = 0 To (e.Row.Cells.Count - 1)
litHeader = New Literal
txtSearch = New CheckBox
' get the current header text
litHeader.Text = e.Row.Cells(i).Text & " "
' add the header text plus a new textbox
e.Row.Cells(i).Controls.Add(txtSearch)
e.Row.Cells(i).Controls.Add(litHeader)
Next
End If
End Sub
Related
I am applying search using a textbox and button and results are shown in GridView in ASP.NET. If result do not match with the search then I want that the Label1 "your search do not match" should be visible.
Here is issue that if search result do not match, Label1 is not called.
the code is given below:
SqlConnection con4 = new SqlConnection("Data Source=***; Initial Catalog=***;Integrated Security=***;");
SqlCommand cmd4 = new SqlCommand("select newsid, title, thumbnail,imagepath,imagename from addnews where (title like'%" + TextBox1.Text.ToString() + "%')", con4);
SqlDataAdapter sda4 = new SqlDataAdapter(cmd4);
DataTable dt4 = new DataTable();
sda4.Fill(dt4);
if (dt4 != null)
{
GridView3.DataSource = dt4;
GridView3.DataBind();
}
else
{
Label1.Visible = true;
}
ASPX markup
<asp:Label ID="Label1" runat="server" ForeColor="Red" Text="Search do not match" Visible="False"></asp:Label>
<asp:GridView ID="GridView3" runat="server"> </asp:GridView>
Refer the below code:
DataTable dt4 = new DataTable();
sda4.Fill(dt4);
if (dt4.Rows.Count > 0)
{
GridView3.DataSource = dt4;
GridView3.DataBind();
}
else
{
Label1.Visible = true;
}
You check for dt4 != null, which will always be true because you initialize it as new Datatable(), so it will never go the "else" part of your statement, but simple put an empty dt4 in the source.
I have DataTable that was loaded with a SqlDataReader query. After my DataTable is loaded, I do looping that I was insert data with a SqlCommand every index. But the DataTable is not refreshed. How to refresh the DataTable while data is updated in the database?
connectionx()
Dim dtreader As SqlDataReader
Dim cmddt As New SqlCommand("SELECT * from sometable", con)
dtreader = cmddt.ExecuteReader()
Dim dt As New System.Data.DataTable()
dt.Load(dtreader) 'Here from datareader
For index As Integer = currentRow To dt.Rows.Count - 1
Dim drR As DataRow = dt.NewRow()
Dim reader1 As SqlDataReader
Dim EP As DateTime
Dim EndW As String = dtnow.ToString("MM/dd/yyyy HH:mm")
Dim setEndWaiting As Integer = Convert.ToInt32(adapterSch.SetEndWTime(EndW, Convert.ToInt32(Session("ShipLoadingOrderFK"))))
Dim startPre As DateTime = EndW
Dim endPre As DateTime = startPre + TimeSpan.Parse(defPre)
Dim setPreDocumentTime As Integer = Convert.ToInt32(adapterSch.SetPreDocumentTime(startPre, endPre, Convert.ToInt32(Session("ShipLoadingOrderFK"))))
Dim startPump As DateTime = endPre
Dim endPump As DateTime
Dim shipKey As String = Shipid.SelectedValue
pumpigResult(MinutePumpResult, HoursPumpResult, FlowrateValue, Shipid.SelectedValue, Loading_No.Value, typeLoading.SelectedValue)
If FlowrateValue = 0 Or FlowrateValue = "" Then
endPump = endPre + TimeSpan.Parse(defPumping)
Else
endPump = endPre + New TimeSpan(HoursPumpResult, MinutePumpResult, 0)
End If
Dim setPumpTime As Integer = Convert.ToInt32(adapterSch.SetPumpingTime(startPump, endPump, Convert.ToInt32(Session("ShipLoadingOrderFK"))))
Dim startPost As DateTime = endPump
Dim endPost As DateTime = endPump + TimeSpan.Parse(defPost)
Dim setPostTime As Integer = Convert.ToInt32(adapterSch.SetPostTime(startPost, endPost, Convert.ToInt32(Session("ShipLoadingOrderFK"))))
After insert data while every index with code above. I have get the value on previous row (index-1), but I get the OLD Data before updated.
Dim EP as datetime = Convert.ToDateTime(dt.Rows(index - 1)("PostDocEnd").ToString())
How to refresh the DataTable so that I can get the previous data that has been updated? I have try to re-load DataTable again, but is nothing.
Thank you
Solved!
I just line code for reload datareader at starting index looping and refresh the datatable.
dt.reset()
dtreader = cmddt.ExecuteReader()
Dim dt As New System.Data.DataTable()
dt.Load(dtreader)
It will be reload the datatable while database is changed.
Hello i am facing the following problem:
I have an excel file that has some cells with dropdown list. I am trying to read the excel and add it to datatable in order to manipulate the data. I have manage to read the excel and add it to datable BUT my method reads all the values that the cells with dropdownlist have, it doesnt read only the one that is selected. For example i gave a cell with three values (1,2,3) and the cell has as selected the value 1. My method reads the excel and adds to the datatable all the values in different rows. So it adds 1,2,3.
You can see my code below:
protected void ddlReviewStatus_SelectedIndexChanged(object sender, EventArgs e)
{
string date = DateTime.Now.ToShortDateString();
string finalDate = date.Replace("/", "");
string fileName = "test.xlsx";
DropDownList ddlReviewStatus = sender as DropDownList;
GridViewRow row = (GridViewRow)ddlReviewStatus.NamingContainer;
string companyName = ((Label)row.FindControl("lblCompName")).Text;
string filePath = ReportTemplatesPath + "\\" + companyName + "\\" + finalDate + "\\" + fileName;
if (ddlReviewStatus.SelectedItem.Text.ToUpper() == "DONE")
{
string extension = Path.GetExtension(fileName);
string conStr = "";
switch (extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"]
.ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"]
.ConnectionString;
break;
}
conStr = String.Format(conStr, filePath,"Yes");
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of First Sheet
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
//Bind Data to GridView
GridView1.Caption = Path.GetFileName(filePath);
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
}
}
I have a combobox in winform which gets data by calling a stored procedure in MySQL.
My stored proc:
CREATE PROCEDURE `GetCourses`()
BEGIN
SELECT course_name FROM my_db.courses where group_id=1;
END
Now the course names are bind with the Combobox(ComboBox2) as below - on selection of another Combobox(ComboBox1):
private void Form_Load(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new MySqlConnection(connectionString);
conn.Open();
MySqlCommand cmd1 = new MySqlCommand();
cmd1.Connection = conn;
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.CommandText = "GetCourses";
DataTable dt1 = new DataTable();
MySqlDataAdapter adp1 = new MySqlDataAdapter(cmd1);
adp1.Fill(dt1);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 3)
{
comboBox2.ValueMember = "course_name";
comboBox2.DisplayMember = "course_name";
comboBox2.DataSource = dt1;
}
}
But when I run the form, the ComboBox is filled with the values as 'system.data.datarowview'
Could anyone please help me with this.
NOTE: I don't want to achieve this by using 'MySqlDataReader'
Thanks in advance.
This is solved simply by below two lines of code.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 3)
{
foreach (DataRow row in dt1.Rows)
comboBox2.Items.Add(row["course_name"]);
}
}
You could project the data into a collection that has named fields to prevent the default ToString()ing of the datarow objects:
if (comboBox1.SelectedIndex == 3)
{
comboBox2.ValueMember = "course_name_value";
comboBox2.DisplayMember = "course_name";
comboBox2.DataSource = dt1.AsEnumerable().Select
(n => new { course_name = n["course_name"], course_name_value = n["course_name"]}).ToList();
}
EDIT
I think you should put these lines in the Load event. You don't need to set them more than once, and it could be the reason for the combobox display getting the object's ToString() result instead of individual properties.
comboBox2.ValueMember = "course_name";
comboBox2.DisplayMember = "course_name";
I ran a mock test, and I think it's disposing of your dataset(when it finished the OnLoad event) before you can get to the selectedIndex changed event. Try having your SelectedIndexChanged event raise a function to populate the second box. PS, don't mind I used an SQLite database to test.
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
If (ComboBox1.SelectedIndex = 3) Then
Select3()
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim range() As String = {"0", "1", "2", "3 - Fire Combo2", "4", "5", "6"}
ComboBox1.Items.AddRange(range)
End Sub
Private Sub Select3()
Dim connectionString As String = MyStandAloneDB.DBConnStr
Dim conn As New System.Data.SQLite.SQLiteConnection(connectionString)
conn.Open()
Dim cmd1 As New System.Data.SQLite.SQLiteCommand
cmd1.Connection = conn
cmd1.CommandType = CommandType.Text
cmd1.CommandText = "SELECT * FROM Foo"
Dim dt1 As New DataTable()
Dim adp1 As New System.Data.SQLite.SQLiteDataAdapter(cmd1)
adp1.Fill(dt1)
ComboBox2.DataSource = dt1
ComboBox2.ValueMember = dt1.Columns(1).ToString
ComboBox2.DisplayMember = dt1.Columns(0).ToString
End Sub
I have 2 gridview called DDLTOC and DDLCase. I have inserted default values into the DDL using appenddatabounditems. My default value is ("Select Member Report ID")
<asp:DropDownList ID="DDLTOC" runat="server" style="margin-top: 0px;" OnSelectedIndexChanged="DDLTOC_SelectedIndexChanged" DataTextField="typeofcrime" DataValueField="typeofcrime" AutoPostBack="True" AppendDataBoundItems="true" >
<asp:ListItem Value="-1">Select Member Report ID</asp:ListItem>
</asp:DropDownList>
DDLCase
<asp:DropDownList ID="DDLCase" runat="server" AutoPostBack="True" DataTextField="memberreportid" DataValueField="memberreportid" Height="16px" OnSelectedIndexChanged="DDLCase_SelectedIndexChanged" AppendDataBoundItems="true" >
<asp:ListItem Value="">Select Case</asp:ListItem>
</asp:DropDownList>
I have inserted data bind into my DDLTOC at the page load which will display selected value from the database once the webapp is run.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;" +
"Initial Catalog=project; Integrated Security = SSPI");
SqlDataAdapter da = new SqlDataAdapter("SELECT distinct typeofcrime FROM MemberReport where handle='handled' AND caseprogress='settled'", conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds);
DDLTOC.DataSource = ds;
DDLTOC.DataTextField = "typeofcrime";
DDLTOC.DataValueField = "typeofcrime";
DDLTOC.DataBind();
conn.Close();
}
}
I also added another bind on the DDLTOC
protected void DDLTOC_SelectedIndexChanged(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = project; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "SELECT memberreportid FROM MemberReport Where typeofcrime ='" + DDLTOC.SelectedValue + "' AND caseprogress='settled'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
DDLCase.DataSource = ds2;
DDLCase.DataTextField = "memberreportid";
DDLCase.DataValueField = "memberreportid";
DDLCase.DataBind();
}
sql = "Select username, memberreportid, location, crdatetime, citizenreport, image1, image2, image3, image4, image5 from MemberReport where typeofcrime ='" + DDLTOC.SelectedItem.Text + "' and handle='handled'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet dsSel = new DataSet();
cmdAdd.Fill(dsSel);
GVCR.DataSource = dsSel;
GVCR.DataBind();
}
connAdd.Close();
}
}
The first binding in DDLTOC_SelectedIndex basically allows the value of DDLCase to be displayed on the dropdownlist according to the value selected in the DDLTOC. The 2nd one binding will display out the necessary values from the database into a gridview. I have 2 database value that will be displayed out in the DDLTOC, Gang & Robbery. So if i were to randomly select gang, then select back to my default value then select gang and back to selecting default value, it will display out the Gang's DDLCase value twice on my DDLCase.
Why does repetitive data occurs?
Before databinding DDLCase, just clear its item collection. Modify your DDLCase databinding code portion as:
DDLCase.Items.Clear();
DDLCase.DataSource = ds2;
DDLCase.DataTextField = "memberreportid";
DDLCase.DataValueField = "memberreportid";
DDLCase.DataBind();
DDLCase.Items.Insert(0, new ListItem("Select Case", ""));
DDLCase.SelectedIndex = 0;
Alternatively you can set EnableViewState="False" in your DDLCase markup; but in that case if any other postback occurs on the page (other than DDLToc, say from a button which does not populate DDLCase again), the data of DDLCase will be lost. It is the ViewState of DDLCase which is keeping the previous state of it so that in cross requests the dropdown items are not lost. And you are just adding into its item collection unless its ViewState is disabled.